package com.shuqi.model;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Picture;
import android.graphics.PointF;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;

import com.shuqi.activity.BookContentActivity;
import com.shuqi.activity.viewport.BookContentBottomView;
import com.shuqi.activity.viewport.BookContentMenuView;
import com.shuqi.activity.viewport.BookContentView;
import com.shuqi.activity.viewport.CataLogLayout;
import com.shuqi.activity.viewport.LeftSliderLayout.OnLeftSliderLayoutStateListener;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.bookcontent.BookContentLoaderThread;
import com.shuqi.bookcontent.BookContentLoaderThread.onBookContentLoaderListener;
import com.shuqi.bookcontent.BookContentRender;
import com.shuqi.common.Constant;
import com.shuqi.common.PayTheme;
import com.shuqi.common.Urls;
import com.shuqi.common.utils.BookContentUtils;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.SharedPreferenceUtil;
import com.shuqi.common.utils.onDrawDataListener;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.BookCataLogDao;
import com.shuqi.database.dao.impl.BookInfoDao;
import com.shuqi.database.dao.impl.TxtCatalogDao;
import com.shuqi.database.model.BookCataLog;
import com.shuqi.database.model.BookInfo;
import com.shuqi.database.model.UserInfo;
import com.shuqi.model.bean.BookContentInfo;
import com.shuqi.model.bean.BookContentLineInfo;
import com.shuqi.model.bean.BookData;
import com.shuqi.model.bean.ChapterInfo;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.model.parse.BookContentParserBase;
import com.shuqi.model.parse.parser.BookContentLocalAppTXTParser;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * 阅读页数据排版处理及绘制内容
 * 
 * @author HuaWei.Yang And Jianda.Yang
 * @date 2013-12-19 下午8:55:51
 * @version 1.0
 */
public class BookContentModel implements BookContentView.OnViewEventListener, onDrawDataListener,
        onBookContentLoaderListener, OnLeftSliderLayoutStateListener, OnItemClickListener,
        OnChildClickListener {
    private Context mContext;
    private WeakReference<BookContentModelStatusListener> mStatusListener;
    private Picture defaultPicture2 = new Picture();
    /** 阅读状态：0,正常阅读；1,购买订单；2,下载提示；3,无网络提示 */
    public int mReadState = READ_STATE_NORMAL;

    /** 0,正常阅读 (default) **/
    public static final int READ_STATE_NORMAL = 0;
    /** 1,购买订单 **/
    public static final int READ_STATE_PAY = 1;
    /** 2,下载提示 **/
    public static final int READ_STATE_DOWNLOAD = 2;
    /** 3,无网络提示 **/
    public static final int READ_STATE_NONET = 3;
    private static final String TAG = "BookContentModel";

    // /** 拖动模式的偏移量(>=textsize+linespace)(<=0) */
    // public float scrollOffset = 0;
    /** 标记当前内容的索引 */
    public int index;
    /** 每页显示几行 */
    public int linesNum;


    private SoftReference<Bitmap> mBackgroundBitmap;
    private SoftReference<Bitmap> mOldContentPageBitmap;
    private SoftReference<Bitmap> mNewContentPageBitmap;
    private Canvas mOldContentPageCanvas;
    private Canvas mNewContentPageCanvas;
    public BookContentView mBookContentView;
    private CataLogLayout mCataLogLayout;
    private BookContentMenuView mBookContentMenuView;
    private UserInfo mUserInfo;

    private String strTitle = "";
    private String strToast = Constant.BOOKCONTENT_BUY_BUTTON_HINT[0];
    private int indexBtnTexts = 0;// btnTexts 索引值

    public final BookContentRender mBookContentRender;
    /** 获取电量广播 */
    public BookContentBottomView mBookContentBottomView;

    /** 是否是加载中 */
    private volatile boolean mIsLoading = false;

    public static enum AsyncUpdateChapterType {
        NONE, PREV, NEXT
    }

    private volatile boolean mIsOptionEnable = true;

    /** 改变字体前当前屏幕第一行第一个字的字节索引值 */
    private int mFirstLineStartByteIndexBeforeSettingChanged = -1;

    /** 是否需要异步更新章节信息，滑动切换页面时本地如果没有缓存数据则需要先显示一个空白页面，等滑动动画结束后再异步加载及显示加载滚动条 */
    private volatile AsyncUpdateChapterType mAsyncUpdateChapterType = AsyncUpdateChapterType.NONE;
    /** 进入阅读页的参数 */
    public BookContentInfo mBookContentInfo;
    private BookContentParserBase mBookContentParserBase;
    private BookInfo mBookInfo;

    /** canvase是否初始化标记：防止反复多次进入/退出阅读页时,频繁创建bitmap,造成内存溢出 */
    private boolean mCanvasHasInit = false;

    /** 动作方向：true,向下翻页;false,向前翻页 */
    private boolean actionDirection = true;// 7.3.9添加

    // TODO---------------------------复制相关-----------------------------
    /** 复制模式起点 */
    private PointF startPoint;
    /** 复制模式终点 */
    private PointF endPoint;
    /** 复制模式的所有文字内容 */
    private List<BookContentLineInfo> copyContentList;
    /** 复制模式真正复制的内容 */
    private StringBuffer copyContent;
    /** 阅读页设置参数 */
    public BookContentSettings settings;
    /** 缓存picture */
    private Picture cachePicture;
    /** 画图所需的paint */
    // 微信图文分享必须设置一个url
    public String contentUrl = "http://ishuqi.com";

    public Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public BookContentModel(Context context, BookContentView bookContentView) {
        mContext = context;
        this.mBookContentView = bookContentView;
        mUserInfo = MyAccountManager.getInstance(mContext);
        mBookContentRender = new BookContentRender(BookContentSettings.getInstance(context));
        settings = BookContentSettings.getInstance(context);
        this.paint.setAntiAlias(true);
        setOnDrawDataListener(this);
    }

    public void setSavedBookContentInfo(BookContentInfo info) {
        mBookContentInfo = info;
        contentUrl = Urls.getWebShuqiBookCoverUrl(mContext, getBookContentInfo().getBookId());
        // Log4an.i("youyang", "-------:"+info.getImageUrl());
        mBookContentInfo.setCurSreenLineCount(getLineNum());
        mBookContentParserBase = BookContentUtils.getBookContentParse(mBookContentInfo.getType());
    }

    public void setCataLogLayout(CataLogLayout cataLogLayout) {
        mCataLogLayout = cataLogLayout;
        mCataLogLayout.setOnLeftSliderLayoutListener(this);
        mCataLogLayout.setOnItemClickListener(this);
    }

    public void setBookContentMenuView(BookContentMenuView view) {
        mBookContentMenuView = view;
    }

    public void setBookContentBottomView(BookContentBottomView view) {
        mBookContentBottomView = view;
        mBookContentBottomView.startUpdateBattery();
    }

    public void setBookContentModelStatusListener(BookContentModelStatusListener statusListener) {
        mStatusListener =
                new WeakReference<BookContentModel.BookContentModelStatusListener>(statusListener);
    }

    public BookContentInfo getBookContentInfo() {
        return mBookContentInfo;
    }

    private void initCanvas() {

        if (mCanvasHasInit) {
            return;
        }
        mCanvasHasInit = true;

        // 创建当前页以及下一页Bitmap
        int width = settings.getScreenWidth();
        int height = settings.getScreenHeight();

        Bitmap tempOldContentPageBitmap = null;
        if (mOldContentPageBitmap == null
                || (tempOldContentPageBitmap = mOldContentPageBitmap.get()) == null
                || tempOldContentPageBitmap.isRecycled()) {
            tempOldContentPageBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
            mOldContentPageBitmap = new SoftReference<Bitmap>(tempOldContentPageBitmap);
        }

        Bitmap tempNewContentPageBitmap = null;
        if (mNewContentPageBitmap == null
                || (tempNewContentPageBitmap = mNewContentPageBitmap.get()) == null
                || tempNewContentPageBitmap.isRecycled()) {
            tempNewContentPageBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
            mNewContentPageBitmap = new SoftReference<Bitmap>(tempNewContentPageBitmap);
        }

        // 设置背景图 8.0后没有用
        // Bitmap tempBackgroundBitmap = null;
        // if (mBackgroundBitmap == null || (tempBackgroundBitmap = mBackgroundBitmap.get()) == null
        // || tempBackgroundBitmap.isRecycled()) {
        // tempBackgroundBitmap =
        // createBackGroundBitmap(PayTheme.findDrawableResIDByName(
        // ShuqiApplication.getContext(), "background"));
        // }

        // 7.3.9主题为图片
        // setBgBitmap(tempBackgroundBitmap);
        // 7.3.7版本图片是纯色，这里先暂时用色值替代图片
        // setBgBitmap(null);
        // setBgThemeId(PayTheme.getCurrentTheme());

        int themeId = PayTheme.getCurrentTheme();
        if (themeId == 0 || themeId == PayTheme.PAY_THEME) {
            setBgBitmap(null);
            setBgThemeId(themeId);
        } else {
            if (themeId == PayTheme.DEFAULT_THEME) {
                if (SharedPreferenceUtil.getInstanceSharedPreferenceUtil()
                        .getBookContentPortraitScreen()) {
                    setBgBitmap(createBigBackGroundBitmap(R.drawable.ptheme1_background));
                } else {
                    setBgBitmap(createBigBackGroundBitmap(R.drawable.ptheme1_background1));
                }
            } else {
                setBgBitmap(createBackGroundBitmap(PayTheme.findDrawableResIDByName(
                        ShuqiApplication.getContext(), "background")));
            }
        }

        // 创建绘制当前页以及下一页的画布canvas
        if (tempOldContentPageBitmap == null)
            mOldContentPageCanvas = new Canvas();
        else
            mOldContentPageCanvas = new Canvas(tempOldContentPageBitmap);

        if (tempNewContentPageBitmap == null)
            mNewContentPageCanvas = new Canvas();
        else
            mNewContentPageCanvas = new Canvas(tempNewContentPageBitmap);

        mBookContentView.setBitmaps(tempOldContentPageBitmap, tempNewContentPageBitmap);
        // 设置翻起页背面的颜色
        mBookContentView.setReadBackBg(Constant.BACK_BG_COLORS[PayTheme.getCurrentTheme()]); // 读取保存到本地的对应主题索引值
        mBookContentView.setViewEnabled(true);
        mBookContentView.setOnViewEventListener(this);
        checkSlideTurnPageSetting();
    }

    public void notifyChangeScreen() {
        // 创建当前页以及下一页Bitmap
        int width = settings.getScreenWidth();
        int height = settings.getScreenHeight();

        if (mOldContentPageBitmap != null && mOldContentPageBitmap.get() != null
                && !mOldContentPageBitmap.get().isRecycled()) {
            mOldContentPageBitmap.get().recycle();
            mOldContentPageBitmap = null;
        }
        if (mNewContentPageBitmap != null && mNewContentPageBitmap.get() != null
                && !mNewContentPageBitmap.get().isRecycled()) {
            mNewContentPageBitmap.get().recycle();
            mNewContentPageBitmap = null;
        }

        Bitmap tempOldContentPageBitmap = null;
        tempOldContentPageBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        mOldContentPageBitmap = new SoftReference<Bitmap>(tempOldContentPageBitmap);

        Bitmap tempNewContentPageBitmap = null;
        tempNewContentPageBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        mNewContentPageBitmap = new SoftReference<Bitmap>(tempNewContentPageBitmap);

        int themeId = PayTheme.getCurrentTheme();
        if (themeId == 0 || themeId == PayTheme.PAY_THEME) {
            setBgBitmap(null);
            setBgThemeId(themeId);
        } else {
            if (themeId == PayTheme.DEFAULT_THEME) {
                if (SharedPreferenceUtil.getInstanceSharedPreferenceUtil()
                        .getBookContentPortraitScreen()) {
                    setBgBitmap(createBigBackGroundBitmap(R.drawable.ptheme1_background));
                } else {
                    setBgBitmap(createBigBackGroundBitmap(R.drawable.ptheme1_background1));
                }
            } else {
                setBgBitmap(createBackGroundBitmap(PayTheme.findDrawableResIDByName(
                        ShuqiApplication.getContext(), "background")));
            }
        }

        // 创建绘制当前页以及下一页的画布canvas
        if (tempOldContentPageBitmap == null)
            mOldContentPageCanvas = new Canvas();
        else
            mOldContentPageCanvas = new Canvas(tempOldContentPageBitmap);

        if (tempNewContentPageBitmap == null)
            mNewContentPageCanvas = new Canvas();
        else
            mNewContentPageCanvas = new Canvas(tempNewContentPageBitmap);

        mBookContentView.setBitmaps(tempOldContentPageBitmap, tempNewContentPageBitmap);
    }

    public void destroy() {
        mBookContentBottomView.stop();
        mCataLogLayout.stopCheck();
        clearAllData();
        onDestory();
        recycledBitmap();
    }

    private Bitmap createBackGroundBitmap(int id) {// 使用bitmap绘制阅读页背景(7.3.7以后用纯色背景，废弃此处的bitmap方式)
        Bitmap tempBackGroundBitmap = null;
        if (mBackgroundBitmap != null && (tempBackGroundBitmap = mBackgroundBitmap.get()) != null
                && !tempBackGroundBitmap.isRecycled()) {
            tempBackGroundBitmap.recycle();
            tempBackGroundBitmap = null;
            mBackgroundBitmap = null;
        }

        // 之前的创建bitmap方式
        // Bitmap tempBitmap =
        // BitmapFactory
        // .decodeResource(ShuqiApplication.getContext().getResources(), id, null);

        InputStream is = mContext.getResources().openRawResource(id);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
        Bitmap tempBitmap = BitmapFactory.decodeStream(is, null, options);

        mBackgroundBitmap = new SoftReference<Bitmap>(tempBitmap);
        return tempBitmap;
    }


    private Bitmap createBigBackGroundBitmap(int id) {
        Bitmap tempBackGroundBitmap = null;
        if (mBackgroundBitmap != null && (tempBackGroundBitmap = mBackgroundBitmap.get()) != null
                && !tempBackGroundBitmap.isRecycled()) {
            tempBackGroundBitmap.recycle();
            tempBackGroundBitmap = null;
            mBackgroundBitmap = null;
        }

        InputStream is = mContext.getResources().openRawResource(id);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
        Bitmap tempBitmap = BitmapFactory.decodeStream(is, null, options);

        // 之前设置背景为一张图，需要将图片等比拉伸
        int width = tempBitmap.getWidth();
        int height = tempBitmap.getHeight();
        float scaleWidth = ((float) settings.getScreenWidth()) / width;
        float scaleHeight = ((float) settings.getScreenHeight()) / height;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        tempBackGroundBitmap = Bitmap.createBitmap(tempBitmap, 0, 0, width, height, matrix, true); // 进行图片等比缩放
        mBackgroundBitmap = new SoftReference<Bitmap>(tempBackGroundBitmap);

        if (tempBitmap != null && tempBitmap != tempBackGroundBitmap) {
            tempBitmap.recycle();
            tempBitmap = null;
        }
        return tempBackGroundBitmap;
    }

    /**
     * 绘制
     * 
     * @param canvas
     */
    public void draw(Canvas canvas, boolean isChangeIndex) {
        switch (mReadState) {
            case READ_STATE_NORMAL: {
                // Log4an.e("yyy",
                // "【绘制】isClickMenuJumpChapter()="+isClickMenuJumpChapter()+",isJumpChapter()="+isJumpChapter());
                if (isClickMenuJumpChapter()) {
                    setJumpChapter(true);
                    setClickMenuJumpChapter(false);
                }
                mBookContentRender.drawReadStateNormalCanvas(canvas,
                        mOnDrawDataListener.getLinesNum(), mOnDrawDataListener.getLineIndex(),
                        mOnDrawDataListener.getCurLines(), mOnDrawDataListener.getNextLines(),
                        mOnDrawDataListener.getPreLines(), mOnDrawDataListener.getByteIndex(),
                        mOnDrawDataListener.actionDirection(), isChangeIndex, isJumpChapter(),
                        isRefreshIndex());
                setJumpChapter(false);
                setRefreshIndex(false);
            }
                break;
            case READ_STATE_PAY: {
                String tempStrTitle =
                        (strTitle == null || "".equals(strTitle)) ? (mBookContentInfo
                                .getCurChapterName() == null ? "" : mBookContentInfo
                                .getCurChapterName()) : strTitle;
                mBookContentRender.drawReadStatePayCanvas(canvas, tempStrTitle, strToast,
                        indexBtnTexts);
                setRefreshIndex(true);
            }
                break;
            case READ_STATE_DOWNLOAD: {

                String tempStrTitle =
                        (strTitle == null || "".equals(strTitle)) ? (mBookContentInfo
                                .getCurChapterName() == null ? "" : mBookContentInfo
                                .getCurChapterName()) : strTitle;
                mBookContentRender.drawReadStatePayCanvas(canvas, tempStrTitle, strToast,
                        indexBtnTexts);
                setRefreshIndex(true);
            }
                break;
            case READ_STATE_NONET:
                break;
        }
    }

    public void onDestory() {
        mBookContentParserBase = null;
        mBookContentRender.destoryBackground();
    }

    private onDrawDataListener mOnDrawDataListener;
    private String copyContent2;


    public void setOnDrawDataListener(onDrawDataListener onDrawDataListener) {
        mOnDrawDataListener = onDrawDataListener;
    }


    /**
     * 设置订单页标题
     * 
     * @param str
     */
    public void setChapterTitle(String str) {
        strTitle = str;
    }

    /**
     * 设置订单提示语
     * 
     * @param str
     */
    public void setOrderPayToast(String str) {
        strToast = str;
    }

    public void setIndexBtnTexts(int indexBtnTexts) {
        this.indexBtnTexts = indexBtnTexts;
    }

    public int getIndexBtnTexts() {
        return indexBtnTexts;
    }

    public void setBgThemeId(int themeId) {
        mBookContentRender.setBgThemeId(themeId);
    }

    public void setBgBitmap(Bitmap bmp) {
        mBookContentRender.resetBackground(bmp);
    }

    /**
     * 从传递过来的字节流中的某一个字节进行前后分行
     * 
     * @throws UnsupportedEncodingException
     * @param list 如果该章已经处理了章节名，则传递包含章节名的list
     * @param data 要排版的数组
     * @param isHeader 是否为标题
     * @param startByte 数组第一个字节的起始索引
     * @param divideByte 数组中要拆分显示的字节索引
     * @param encoding 字节内容的编码
     * @return
     * @throws UnsupportedEncodingException
     */
    // public List<BookContentLineInfo> getLineinfosByIndex(List<BookContentLineInfo> list,
    // byte[] data, boolean isHeader, int startByte, int divideByte, String encoding)
    // throws UnsupportedEncodingException {
    // return mBookContentRender.getLineinfosByIndex(list, data, isHeader, startByte, divideByte,
    // encoding, mOnDrawDataListener.getBookType());
    // }


    public BookContentRender getBookContentRender() {
        return mBookContentRender;
    }

    public void setTypeDonwload(String chapterName, int toastIndex) {
        controlBuyButtonIsClick(true);
        mReadState = BookContentModel.READ_STATE_PAY;
        setChapterTitle(chapterName);
        setOrderPayToast(Constant.BOOKCONTENT_BUY_BUTTON_HINT[toastIndex]);
        setIndexBtnTexts(BookContentRender.BOOK_CONTENT_BUTTON_TEXT_RETRY);
        mBookContentInfo.refreshCurChapterContentLines(mBookContentRender,
                mBookContentInfo.getMarkIndex());
        mBookContentInfo.setCurChapterLineIndex(0);
    }

    /***
     * 用户未登录
     * 
     * @param chapterName
     */
    public void setTypeNoLogin(String chapterName) {
        mReadState = BookContentModel.READ_STATE_PAY;
        setChapterTitle(chapterName);
        setOrderPayToast(Constant.BOOKCONTENT_BUY_BUTTON_HINT[4]);
        setIndexBtnTexts(3);
    }

    /***
     * 登陆请求返回错误
     * 
     * @param chapterName
     */
    public void setTypeRequestCode(String chapterName) {
        mReadState = BookContentModel.READ_STATE_PAY;
        setChapterTitle(chapterName);
        setOrderPayToast(Constant.BOOKCONTENT_BUY_BUTTON_HINT[4]);
        setIndexBtnTexts(BookContentRender.BOOK_COTNENT_BUTTON_TEXT_BUY);
    }

    /***
     * 已经购买
     * 
     * @param chapterName
     */
    public void setTypePay(String chapterName) {
        mReadState = BookContentModel.READ_STATE_PAY;
        setChapterTitle(chapterName);
        setOrderPayToast(Constant.BOOKCONTENT_BUY_BUTTON_HINT[3]);
        setIndexBtnTexts(BookContentRender.BOOK_CONTENT_BUTTON_TEXT_COVER);
    }

    public void renderNewContentPage(final boolean isChangeIndex) {
        postTaskToUiThread(new Runnable() {
            @Override
            public void run() {
                draw(mNewContentPageCanvas, isChangeIndex);
            }
        });
    }

    public void renderOldContentPage(final boolean isChangeIndex) {
        postTaskToUiThread(new Runnable() {
            @Override
            public void run() {
                draw(mOldContentPageCanvas, isChangeIndex);
            }
        });
    }

    public void postInvalidate() {
        mBookContentView.postInvalidateRefresh();
    }

    public void blockBookContentView(boolean block) {
        mBookContentView.setViewEnabled(block);
    }

    /**
     * 清理图片
     */
    public void recycledBitmap() {
        // 图片缓存起来，避免反复创建
        if (mBackgroundBitmap != null && mBackgroundBitmap.get() != null
                && !mBackgroundBitmap.get().isRecycled()) {
            mBackgroundBitmap.get().recycle();
            mBackgroundBitmap = null;
        }
        if (mOldContentPageBitmap != null && mOldContentPageBitmap.get() != null
                && !mOldContentPageBitmap.get().isRecycled()) {
            mOldContentPageBitmap.get().recycle();
            mOldContentPageBitmap = null;
        }
        if (mNewContentPageBitmap != null && mNewContentPageBitmap.get() != null
                && !mNewContentPageBitmap.get().isRecycled()) {
            mNewContentPageBitmap.get().recycle();
            mNewContentPageBitmap = null;
        }
    }

    public void turnPrevPage() {
        mBookContentView.doTurnPrevPage(false);
    }

    public void turnNextPage() {
        mBookContentView.doTurnNextPage();
    }

    public void notifyThemeChanged(int themeId) {
        // 设置翻起页背面的颜色
        mBookContentView.setReadBackBg(Constant.BACK_BG_COLORS[PayTheme.getCurrentTheme()]);
        // 设置翻页时右面的色条
        mBookContentView.setCurBitmapShadow(Constant.READ_RIGHT_COLORS[PayTheme.getCurrentTheme()]);
        // 设置对应皮肤下仿真翻页的阴影颜色值
        mBookContentView.setModeBookShadow(PayTheme.getCurrentTheme());

        // 7.3.9背景为图片
        // setBgBitmap(createBackGroundBitmap(PayTheme.findDrawableResIDByName(
        // ShuqiApplication.getContext(), "background")));
        // 7.3.8版本图片是纯色，这里先暂时用色值替代图片
        // setBgBitmap(null);
        // setBgThemeId(themeId);

        if (themeId == 0 || themeId == PayTheme.PAY_THEME) {
            setBgBitmap(null);
            setBgThemeId(themeId);
        } else {
            if (themeId == PayTheme.DEFAULT_THEME) {
                // setBgBitmap(createBigBackGroundBitmap(PayTheme.findDrawableResIDByName(
                // ShuqiApplication.getContext(), "background")));
                if (SharedPreferenceUtil.getInstanceSharedPreferenceUtil()
                        .getBookContentPortraitScreen()) {
                    setBgBitmap(createBigBackGroundBitmap(R.drawable.ptheme1_background));
                } else {
                    setBgBitmap(createBigBackGroundBitmap(R.drawable.ptheme1_background1));
                }
            } else {
                setBgBitmap(createBackGroundBitmap(PayTheme.findDrawableResIDByName(
                        ShuqiApplication.getContext(), "background")));
            }
        }

        renderNewContentPage(false);
        postInvalidate();
        mBookContentBottomView.refresh();
    }

    public void checkSlideTurnPageSetting() {
        boolean isSideTurnPgae =
                SharedPreferenceUtil.getInstanceSharedPreferenceUtil().getBookContentTurnPageMode();
        mBookContentView.setIsClickSideTurnPage(isSideTurnPgae); // 读取是否是点击两侧翻页
    }

    public void checkTurnMode() {
        int mPageTurnMode =
                SharedPreferenceUtil.getInstanceSharedPreferenceUtil().getBookContentPageTurnMode();
        settings.setmPageTurnMode(mPageTurnMode);
        mBookContentView.setPageTurnMode(mPageTurnMode);
    }

    @Override
    public int onViewClick(ClickAction action) {
        switch (action) {
            case MENU:
                mBookContentMenuView.mWhich = Constant.MENU_FIRST_LAYOUT;
                mBookContentMenuView.setMenuEnable(true);
                mBookContentMenuView.setVisibility(View.VISIBLE, true, mBookContentMenuView.mWhich);
                blockBookContentView(false);

                if (mBookContentInfo.getType() == Constant.BOOKTYPE_NET) {
                    if (isStatusListenerValid()) {
                        ShuqiApplication.getApplicationHandler().postDelayed(new Runnable() {
                            public void run() {
                                mStatusListener.get().onShowOrigin(getTheSourceLink());
                            }
                        }, 300);
                    }
                }
                StatisticsUtils.onEvent(StatisticsEventID.BOOKCONTENT_CALL_MENU);
                return BookContentView.DIRECTION_OTHER;
            case PREV_PAGE:
                StatisticsUtils.onEvent(StatisticsEventID.BOOKCONTENT_PRE_PAGE);
                return loadPrePage();
            case NEXT_PAGE:
                StatisticsUtils.onEvent(StatisticsEventID.BOOKCONTENT_NEXIT_PAGE);
                return loadNextPage();
            default:
                return BookContentView.DIRECTION_VOID;
        }
    }

    @Override
    public void onAnimationFinished() {
        if (isNeedAsyncUpdateChapter()) {
            asyncUpdateChapter(mAsyncUpdateChapterType == AsyncUpdateChapterType.NEXT);
        } else {
            setAsyncUpdateChapterType(AsyncUpdateChapterType.NONE);
        }
    }

    @Override
    public boolean onLoadNextPage(int scrollDirection) {
        switch (scrollDirection) {
            case BookContentView.DIRECTION_LEFT:// 翻下一页时
                StatisticsUtils.onEvent(StatisticsEventID.BOOKCONTENT_NEXIT_PAGE);
                return BookContentView.DIRECTION_OTHER == loadNextPage();
            case BookContentView.DIRECTION_RIGHT:// 翻上一页
                StatisticsUtils.onEvent(StatisticsEventID.BOOKCONTENT_PRE_PAGE);
                return BookContentView.DIRECTION_OTHER == loadPrePage();
        }
        return false;
    }

    /***
     * 非付费加载逻辑
     */
    private int loadNextNormalPage() {
        moveToNormalNextPage();
        refreshView(true);
        mBookContentRender.setChangeCurLineSize(false);
        return BookContentView.DIRECTION_LEFT;
    }

    /***
     * 刷新页面
     * 
     * @param isNext 是否在nextCanvas上渲染
     */
    private void refreshView(boolean isNext) {
        showTopTitle();
        actionDirection = isNext;
        renderNewContentPage(true);
        showPercent(true);
        postInvalidate();
    }

    @Override
    public void onViewTouchEnd(int scrollDirection, boolean isBack) {
        if (isBack) {
            setAsyncUpdateChapterType(AsyncUpdateChapterType.NONE);
            switch (scrollDirection) {
                case BookContentView.DIRECTION_LEFT:
                    loadPrePage();
                    break;
                case BookContentView.DIRECTION_RIGHT:
                    loadNextPage();
                    break;
            }
        }
    }

    @Override
    public void onViewSizeChanged() {
        // drawCopyMode(0);
    }

    public void setStartUpdateTime() {
        mBookContentBottomView.startUpdateTime();
    }

    public boolean isOrderPay() {
        return mBookContentInfo.getType() == Constant.BOOKTYPE_ORDER_PAY;
    }

    /**
     * 获取绘制的行数
     * 
     * @return
     */
    private int getLineNum() {
        return mStatusListener.get().onScreenVisibleLineNum();
    }

    /**
     * 清除缓存的：上章、当章、下章，以及他们的排版数据
     */
    public void clearAllData() {
        mBookContentInfo.clearAll();
    }

    private synchronized void setIsLoading(boolean isLoading) {
        mIsLoading = isLoading;
        if (!isLoading && isStatusListenerValid()) {
            mStatusListener.get().onLoadingStatusChanged(false, true);
        }
    }

    private synchronized void openSetIsLoading(boolean isLoading) {
        mIsLoading = isLoading;
        if (!isLoading && isStatusListenerValid()) {
            mStatusListener.get().onOpenLoadingStatusChanged(false);
        }
    }

    public boolean isLoading() {
        return mIsLoading;
    }

    private synchronized void setAsyncUpdateChapterType(AsyncUpdateChapterType type) {
        mAsyncUpdateChapterType = type;
    }

    private boolean isNeedAsyncUpdateChapter() {
        return mAsyncUpdateChapterType != AsyncUpdateChapterType.NONE;
    }

    /** 设置改变了：字体大小，行间距，翻页模式 */
    public void notifyUpdateSettingsChanged() {
        if (mBookContentInfo.getCurChapter().getContentLines() == null)
            return;

        // TODO 获取通知栏高度
        mStatusListener.get().setStatusBarHeight(
                SharedPreferenceUtil.getInstanceSharedPreferenceUtil().getBookContentFullScreen());
        mBookContentBottomView.setStatusBarHeight(mStatusListener.get().getStatusBarHeight());

        // Log4an.e("yyy",
        // "【notifyUpdateSettingsChanged】LineIndex=" + mBookContentRender.getFirstLineIndex());
        mBookContentInfo.setCurChapterLineIndex(mBookContentRender.getFirstLineIndex());
        // Log4an.e("yyy", "getCurChapterLineIndex=" + mBookContentInfo.getCurChapterLineIndex());
        if (mFirstLineStartByteIndexBeforeSettingChanged < 0
                && mBookContentInfo.getCurChapterContentLines().size() > mBookContentInfo
                        .getCurChapterLineIndex()) {
            mFirstLineStartByteIndexBeforeSettingChanged =
                    mBookContentInfo.getCurChapterContentLines()
                            .get(mBookContentInfo.getCurChapterLineIndex()).getFirstIndex();
            // Log4an.e("yyy", "1.mFirstLineStartByteIndexBeforeSettingChanged="
            // + mFirstLineStartByteIndexBeforeSettingChanged);
        }
        // Log4an.e("yyy",
        // "【notifyUpdateSettingsChanged】mFirstLineStartByteIndexBeforeSettingChanged="
        // + mFirstLineStartByteIndexBeforeSettingChanged + ",首行字节索引="
        // + mBookContentRender.getmCurLinesFirstByteIndex());
        mBookContentInfo.getCurChapter().setStartIndex(
                mBookContentRender.getmCurLinesFirstByteIndex());

        mBookContentInfo.setCurSreenLineCount(getLineNum());

        mBookContentRender.setNotifyChangeSetting(true);

        mBookContentInfo.doProcessSettingChanged(mBookContentRender,
                mFirstLineStartByteIndexBeforeSettingChanged);
        BookContentUtils.calcPageLineIndex(mBookContentInfo,
                mFirstLineStartByteIndexBeforeSettingChanged);

        notifyUpdateDataChanged(true);

        mBookContentRender.setNotifyChangeSetting(false);
    }

    /**
     * 执行跳转章节或翻页等操作后重置该记录
     */
    private void resetFirstLineStartByteIndexBeforeSettingChanged() {
        mFirstLineStartByteIndexBeforeSettingChanged = -1;
    }

    /**
     * 按本购买成功，去封面下载提示
     */
    public int refreshDownView() {
        blockBookContentView(true);
        if (isStatusListenerValid()) {
            mStatusListener.get().onNeedBuyStatusChanged(true);
            mStatusListener.get().onLoadingStatusChanged(false, false);
        }
        setTypePay(mBookContentInfo.getCurChapterName());
        blockBookContentView(true);
        notifyUpdateDataChanged(true);
        return BookContentView.DIRECTION_OTHER;
    }

    /** 初始化进入阅读页：需要参数：BookContentParams：params */
    public void loadPage(boolean isInit) {

        if (isValidBookInfo(mBookContentInfo) == false || isLoading() == true) {
            return;
        }

        // setIsLoading(true);
        openSetIsLoading(true);
        resetFirstLineStartByteIndexBeforeSettingChanged();
        blockBookContentView(false);
        clearAllData();
        // if (isStatusListenerValid()) {
        // mStatusListener.get().onLoadingStatusChanged(true);
        // }
        if (isStatusListenerValid()) {
            mStatusListener.get().onOpenLoadingStatusChanged(true);
        }
        refreshCurView(isInit);
    }

    private void refreshCurView(boolean isInit) {
        BookContentLoaderThread sThread =new BookContentLoaderThread(ShuqiApplication.getContext(), mBookContentInfo,mBookContentParserBase, isInit);
        sThread.setBookContentModel(this);
        sThread.setBookContentLoaderListener(this);
        sThread.start();
    }



    /**
     * 显示顶部标题(或章节名称)
     */
    public void showTopTitle() {
        postTaskToUiThread(new Runnable() {
            @Override
            public void run() {
                String chapterName = "";
                List<BookContentInfo> catalog =
                        TxtCatalogDao.getInstance().getTxtCatalogListByFilePath(
                                mBookContentInfo.getFliePath());
                if (mBookContentInfo.getType() == Constant.BOOKTYPE_TXT
                        && (catalog == null || catalog.size() <= 0)) {
                    chapterName = mBookContentInfo.getBookname();
                } else {
                    chapterName =
                            mBookContentInfo.getCurChapterName() == null ? mBookContentInfo
                                    .getBookname() : mBookContentInfo.getCurChapterName();
                }
                mBookContentRender.setTitle(chapterName);
            }
        });
    }

    /** 通知更新默认画面 */
    public void notifyUpdateDataChanged(boolean isChange) {
        // Log.d(TAG, "【收费版】2222222222222222222");
        renderNewContentPage(isChange);
        postInvalidate();
        // 画面更新完成执行更新菜单数据
        if (mBookContentMenuView != null && mBookContentMenuView.isShown()) {
            mBookContentMenuView.onBookContentComplete();
        }
    }

    /** 判断是否阅读页可用 */
    public boolean isBookContentEnabled() {
        return mBookContentInfo.isBookContentEnabled();
    }

    private int loadNextPayPage() {
        // Log4an.i(
        // "draw",
        // "【loadNextPayPage】nextCid=" + mBookContentInfo.getNextChapterCid() + ",type="
        // + mBookContentInfo.getType() + ",curType="
        // + mBookContentInfo.getCurChapterType());
        if (mBookContentInfo.getNextChapterCid() == null) {
            return BookContentView.DIRECTION_OTHER;
        }

        mBookContentInfo.setType(BookContentUtils.TYPE_NEDD_BUY.equals(mBookContentInfo
                .getCurChapterType()) ? Constant.BOOKTYPE_ORDER_PAY : Constant.BOOKTYPE_PAY);
        mBookContentInfo.setNeedBuy(getNeedBuyState());

        // Log4an.i("draw",
        // "mBookContentInfo.getCurChapterType()=" + mBookContentInfo.getCurChapterType()
        // + ",type=" + mBookContentInfo.getType());
        if (BookContentUtils.TYPE_HAS_READ.equals(mBookContentInfo.getCurChapterType())) {
            setRefreshIndex(false);
            moveToNormalNextPage();
        } else {
            moveToNextChapter();
        }
        refreshView(true);
        return BookContentView.DIRECTION_LEFT;
    }

    private void resetChapterPay() {
        controlBuyButtonIsClick(true);
        StatisticsUtils.onEvent(StatisticsEventID.BOOKCONTENT_ENTER_NO_BUY_CHAPTER);
        mBookContentInfo.setType(Constant.BOOKTYPE_ORDER_PAY);
        mReadState = BookContentModel.READ_STATE_PAY;
        setChapterTitle(mBookContentInfo.getCurChapterName());
        setOrderPayToast(Constant.BOOKCONTENT_BUY_BUTTON_HINT[0]);
        setIndexBtnTexts(BookContentRender.BOOK_COTNENT_BUTTON_TEXT_BUY);
    }

    /**
     * 获取收费模式
     * 
     * @remark 支付模式: 0免费章节; 1全本; 2按章;3全本免费章节;-4 需要购买
     * @param payMode
     * @return
     */
    private boolean getNeedBuyState() {
        BookInfo bookInfo =
                BookInfoDao.getInstance().getBookInfo(null, mBookContentInfo.getBookId(),
                        mBookContentInfo.getUid());
        // Log4an.i("yjd",
        // "bookInfo is null="+(bookInfo==null?true:bookInfo.getBookAutoBuyState()));
        if (bookInfo == null) {
            return false;
        }
        if (BookInfo.DEFAULT_NO_AUTO_BUY == bookInfo.getBookAutoBuyState()
                || BookInfo.NO_AUTO_BUY == bookInfo.getBookAutoBuyState()) {
            return true;
        } else if (BookInfo.AUTO_BUY == bookInfo.getBookAutoBuyState()) {
            return false;
        }
        // Log4an.i("yjd", "***********retrun false*******");
        return false;
    }


    /**
     * 加载下一页
     * 
     * @return 0 翻页失败
     */
    private int loadNextPage() {
        if (!verifyMenuOptionAvailability() || isLoading())
            return BookContentView.DIRECTION_OTHER;
        setIsLoading(true);
        resetFirstLineStartByteIndexBeforeSettingChanged();
        actionDirection = true;
        renderOldContentPage(false);
        // Log4an.e(
        // "draw",
        // "【loadNextPage】isOrderPay()=" + isOrderPay() + ",type="
        // + mBookContentInfo.getType());
        final int result =
                hasNextChapter() ? (isOrderPay() ? loadNextPayPage() : loadNextNormalPage())
                        : BookContentView.DIRECTION_OTHER;
        setIsLoading(false);
        return result;
    }

    public boolean hasNextChapter() {
        mBookContentInfo.setCurChapterLineIndex(mBookContentRender.getFirstLineIndex());
        mBookContentInfo.setCurSreenLineCount(mBookContentRender.getCurLineNum());
        // Log4an.i("draw",
        // "【hasNextChapter】curLineIndex=" + mBookContentInfo.getCurChapterLineIndex()
        // + ",CurSreenLineCount=" + mBookContentInfo.getCurSreenLineCount());
        // 没有下一章时
        if (mBookContentInfo.hasNotNextPage(mBookContentParserBase)
                || downloadFeildErrorHasNextChapter()) {
            notifyHasNoNextChapterToast();
            return false;
        }

        return true;
    }

    public boolean hasPreChapter() {
        mBookContentInfo.setCurChapterLineIndex(mBookContentRender.getFirstLineIndex());
        mBookContentInfo.setCurSreenLineCount(mBookContentRender.getCurLineNum());
//        Log4an.i("draw", "【hasPreChapter】curLineIndex=" + mBookContentInfo.getCurChapterLineIndex()
//                + ",CurSreenLineCount=" + mBookContentInfo.getCurSreenLineCount());
        // 没有上一章时
        if (mBookContentInfo.hasNotPrevPage(mBookContentParserBase)) {
            notifyHasNoPrevChapterToast();
            return false;
        }

        return true;
    }

    private boolean downloadFeildErrorHasNextChapter() {
        // Log4an.i(
        // "draw",
        // "【downloadFeildErrorHasNextChapter】mBookContentInfo.getCurChapterType()="
        // + mBookContentInfo.getCurChapterType() + ",nextCid="
        // + mBookContentInfo.getNextChapterCid());
        if ((BookContentUtils.TYPE_NO_NET.equals(mBookContentInfo.getCurChapterType()) || BookContentUtils.TYPE_DOWN_FAIL
                .equals(mBookContentInfo.getCurChapterType()))
                && TextUtils.isEmpty(mBookContentInfo.getNextChapterCid())) {
            return true;
        }
        return false;
    }

    private void notifyHasNoNextChapterToast() {
        if (isStatusListenerValid()) {
            if (mBookContentInfo.getType() == Constant.BOOKTYPE_BAG) {
                mStatusListener.get().onReadBagEnd(mBookContentInfo.getBookId(),
                        mBookContentInfo.getBookname());
            } else {
                mStatusListener.get().onShowMsg(R.string.unfind_next_chapter);
            }
        }
    }

    private void notifyHasNoPrevChapterToast() {
        if (isStatusListenerValid()) {
            mStatusListener
                    .get()
                    .onShowMsg(
                            mBookContentInfo.getType() == Constant.BOOKTYPE_BAG ? R.string.haveReadWholeBookPackage
                                    : R.string.unfind_pre_chapter);
        }
    }


    private int loadPrePage() {
        if (!verifyMenuOptionAvailability() || isLoading())
            return BookContentView.DIRECTION_OTHER;
        setIsLoading(true);
        resetFirstLineStartByteIndexBeforeSettingChanged();
        actionDirection = false;
        renderOldContentPage(false);
        // Log4an.i("draw", "【loadPrePage】types=" + mBookContentInfo.getType());
        final int result = isOrderPay() ? loadPrePayPage() : loadPrevNormalPage();
        setIsLoading(false);
        return result;
    }

    private int loadPrePayPage() {

        if (mBookContentInfo.getPreChapterCid() == null) {
            return BookContentView.DIRECTION_OTHER;
        }

        mBookContentInfo.setType(Constant.BOOKTYPE_PAY);
        mBookContentInfo.setNeedBuy(getNeedBuyState());
        // Log4an.i(
        // "draw",
        // "【loadPrePayPage】mBookContentInfo.getCurChapterType()="
        // + mBookContentInfo.getCurChapterType());
        if (BookContentUtils.TYPE_HAS_READ.equals(mBookContentInfo.getCurChapterType())) {
            setRefreshIndex(false);
            moveToNomalPrevPage();
        } else {
            moveToPreChapter();
        }
        refreshView(false);
        return BookContentView.DIRECTION_RIGHT;
    }

    /***
     * 正常阅读过程中的文本跳转到下一页
     * 
     * @return 翻页或者翻章的操作是否被执行.
     */
    private void moveToNormalNextPage() {
        mBookContentInfo.setCurChapterLineIndex(mBookContentRender.getFirstLineIndex());
        mBookContentInfo.setCurSreenLineCount(mBookContentRender.getCurLineNum());
        // Log4an.i(
        // "draw",
        // "【moveToNormalNextPage】curLineIndex=" + mBookContentInfo.getCurChapterLineIndex()
        // + ",CurSreenLineCount=" + mBookContentInfo.getCurSreenLineCount() + ",cid="
        // + mBookContentInfo.getCurChapterCid() + ",isValid="
        // + mBookContentInfo.getCurChapter().isValid() + ",preCid="
        // + mBookContentInfo.getPreChapterCid() + ",nextCid="
        // + mBookContentInfo.getNextChapterCid());
        // 跳下一章
        if (!mBookContentInfo.getCurChapter().isValid()
                || mBookContentInfo.getCurChapterLineIndex()
                        + mBookContentInfo.getCurSreenLineCount() >= mBookContentInfo
                        .getCurChapterContentLines().size()) {
            mBookContentRender.setChangeCurLineSize(true);
            moveToNextChapter();
        } else {
            mBookContentInfo.curChapterLineIndexChanged(mBookContentInfo.getCurSreenLineCount());
        }
    }

    private void moveToNomalPrevPage() {
//        Log4an.i(
//                "draw",
//                "【moveToNomalPrevPage】curLineIndex="
//                        + mBookContentInfo.getCurChapterLineIndex()
//                        + ",CurSreenLineCount="
//                        + mBookContentInfo.getCurSreenLineCount()
//                        + ",差值="
//                        + (mBookContentInfo.getCurChapterLineIndex() - mBookContentInfo
//                                .getCurSreenLineCount()));
        if (!mBookContentInfo.getCurChapter().isValid()
                || (mBookContentInfo.getCurChapterLineIndex() <= 0 && mBookContentInfo
                        .getCurChapterLineIndex() - mBookContentInfo.getCurSreenLineCount() < 0)) {
            mBookContentRender.setChangeCurLineSize(true);
            moveToPreChapter();
        } else {
            mBookContentInfo.curChapterLineIndexChanged(-mBookContentInfo.getCurSreenLineCount());
        }
    }

    private void moveToPreChapter() {
//        Log4an.i(
//                "draw",
//                "【***moveToPreChapter***】curCid=" + mBookContentInfo.getCurChapterCid()
//                        + ",preCid=" + mBookContentInfo.getPreChapterCid() + ",nextCid="
//                        + mBookContentInfo.getNextChapterCid() + ",type="
//                        + mBookContentInfo.getType());
        if (mBookContentInfo.getType() == Constant.BOOKTYPE_PAY
                && !TextUtils.isEmpty(mBookContentInfo.getPreChapterCid())) {
            mBookContentInfo.moveToPrevChapter();
        } else {
            mBookContentInfo.moveToPrevChapter();
        }
        // Log4an.e(
        // "draw",
        // "bid="
        // + mBookContentInfo.getBookId()
        // + ",cid="
        // + mBookContentInfo.getCurChapterCid()
        // + ",uid="
        // + mBookContentInfo.getUid()
        // + ",是否有缓存："
        // + mBookContentParserBase.hasLocalCachedData(mBookContentInfo.getBookId(),
        // mBookContentInfo.getSourceId(),
        // mBookContentInfo.getCurChapterCid(), mBookContentInfo.getUid()));
        if (mBookContentParserBase.hasLocalCachedData(mBookContentInfo.getBookId(),
                mBookContentInfo.getSourceId(), mBookContentInfo.getCurChapterCid(),
                mBookContentInfo.getUid())
                || BookContentUtils.getIsNeedBuy(mContext, mBookContentInfo)) {
//            Log4an.w("draw", "[moveToPreChapter]111111111111111111111111");
            updatePrevChapter();
        } else {
//            Log4an.w("draw", "[moveToPreChapter]222222222222222222222222");
            setAsyncUpdateChapterType(AsyncUpdateChapterType.PREV);
        }
    }

    private void updatePrevChapter() {
        mBookContentParserBase.getCurInfos(ShuqiApplication.getContext(), mBookContentInfo, false);
        mBookContentInfo.resetPayType();
        // Log4an.e("draw", "【updatePrevChapter】isNetBook()=" + isNetBook());
        if (isNetBook()) {
            // Log4an.e(
            // "draw",
            // "【updatePrevChapter】getCurChapterType()="
            // + mBookContentInfo.getCurChapterType());
            if (TextUtils.isEmpty(mBookContentInfo.getCurChapterType())) {
                setNullCurChapterType();
            }
            if (BookContentUtils.TYPE_HAS_READ.equals(mBookContentInfo.getCurChapterType())) {
                resetChapterNormal();
                // Log4an.e("2", "【updatePrevChapter】getMarkIndex=" +
                // mBookContentInfo.getMarkIndex());
                mBookContentInfo.refreshCurChapterContentLines(mBookContentRender,
                        mBookContentInfo.getMarkIndex());

                // TODO 7.3.9暂时屏蔽，有待调试 by Jianda.Yang
                // if (mBookContentInfo.getCurChapter().isValid()) {
                // Log4an.e("2", "getCurChapterContentLines="
                // + mBookContentInfo.getCurChapterContentLines().size());
                // int remaind = 0;
                // if (mBookContentInfo.getCurSreenLineCount() != 0) {
                // remaind =
                // mBookContentInfo.getCurChapterContentLines().size()
                // % mBookContentInfo.getCurSreenLineCount();
                // }
                // mBookContentInfo.setCurChapterLineIndex(Math.max(
                // mBookContentInfo.getCurChapterContentLines().size()
                // - (remaind == 0 ? mBookContentInfo.getCurSreenLineCount()
                // : remaind), 0));
                // } else {
                // mBookContentInfo.setCurChapterLineIndex(0);
                // }
            } else if (BookContentUtils.TYPE_DOWN_FAIL.equals(mBookContentInfo.getCurChapterType())) {
                // setJumpChapter(true);
                setTypeDonwload(mBookContentInfo.getCurChapterName(), 1);
            } else if (BookContentUtils.TYPE_NO_NET.equals(mBookContentInfo.getCurChapterType())) {
                // setJumpChapter(true);
                setTypeDonwload(
                        TextUtils.isEmpty(mBookContentInfo.getCurChapterName()) ? mBookContentInfo.getBookname()
                                : mBookContentInfo.getCurChapterName(), 1);
            } else if (BookContentUtils.TYPE_GET_CATALOG_FAIL.equals(mBookContentInfo
                    .getCurChapterType())) {
                // setJumpChapter(true);
                setTypeDonwload(
                        TextUtils.isEmpty(mBookContentInfo.getCurChapterName()) ? mBookContentInfo.getBookname()
                                : mBookContentInfo.getCurChapterName(), 5);
            } else {
                // setJumpChapter(true);
                resetChapterPay();
            }
        } else {
            mBookContentInfo.refreshCurChapterContentLines(mBookContentRender,
                    mBookContentInfo.getMarkIndex());
            if (mBookContentInfo.getCurChapter().isValid()) {
                int remaind =
                        mBookContentInfo.getCurChapterContentLines().size()
                                % mBookContentInfo.getCurSreenLineCount();
                mBookContentInfo
                        .setCurChapterLineIndex(Math.max(
                                mBookContentInfo.getCurChapterContentLines().size()
                                        - (remaind == 0 ? mBookContentInfo.getCurSreenLineCount()
                                                : remaind), 0));
            } else {
                mBookContentInfo.setCurChapterLineIndex(0);
            }
        }
    }

    private void asyncUpdateChapter(final boolean isNext) {
        setIsLoading(true);
        if (isStatusListenerValid()) {
            mStatusListener.get().onLoadingStatusChanged(true, false);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {

                boolean lastType =
                        Constant.BOOKTYPE_PAY == mBookContentInfo.getType()
                                || Constant.BOOKTYPE_ORDER_PAY == mBookContentInfo.getType();

                if (isNext) {
                    updateNextChapter();
                } else {
                    updatePrevChapter();
                }

                /***
                 * 如果获取数据之前为需要付费的状态,并且当前的返回状态为正常阅读 则为自动购买状态
                 */
                if (lastType
                        && BookContentUtils.TYPE_HAS_READ.equals(mBookContentInfo
                                .getCurChapterType())) {
                    notifyCatalogLayoutPayState();
                }

                setIsLoading(false);
                refreshView(isNext);
                setAsyncUpdateChapterType(AsyncUpdateChapterType.NONE);
            }
        }).start();
    }

    private void notifyCatalogLayoutPayState() {
        postTaskToUiThread(new Runnable() {
            @Override
            public void run() {
                mCataLogLayout.resetChapterPayModel2NoPay(mBookContentInfo.getCurChapterCid());
            }
        });
    }

    /***
     * 正常阅读需要跳章
     */
    private void moveToNextChapter() {
        // Log4an.i(
        // "draw",
        // "【***moveToNextChapter***】curCid=" + mBookContentInfo.getCurChapterCid()
        // + ",preCid=" + mBookContentInfo.getPreChapterCid() + ",nextCid="
        // + mBookContentInfo.getNextChapterCid() + ",type="
        // + mBookContentInfo.getType());
        if (mBookContentInfo.getType() == Constant.BOOKTYPE_PAY) {
            if (!TextUtils.isEmpty(mBookContentInfo.getNextChapterCid()))
                mBookContentInfo.moveToNextChapter();
        } else {
            mBookContentInfo.moveToNextChapter();
        }
        processMoveToNextChapterOption();
    }

    /***
     * 控制移动到下一章的操作为同步或者异步处理
     */
    private void processMoveToNextChapterOption() {
        // Log4an.i("draw",
        // "【processMoveToNextChapterOption】curCid=" + mBookContentInfo.getCurChapterCid()
        // + ",preCid=" + mBookContentInfo.getPreChapterCid() + ",nextCid="
        // + mBookContentInfo.getNextChapterCid());
        if (mBookContentParserBase.hasLocalCachedData(mBookContentInfo.getBookId(),
                mBookContentInfo.getSourceId(), mBookContentInfo.getCurChapterCid(),
                mBookContentInfo.getUid())
                || BookContentUtils.getIsNeedBuy(mContext, mBookContentInfo)) {
            updateNextChapter();
        } else {
            // Log4an.d("draw", "【*************************】");
            setAsyncUpdateChapterType(AsyncUpdateChapterType.NEXT);
        }
    }

    /**
     * 当mBookContentInfo.getCurChapterType()获取为空时，冗余设置CurChapterType数据
     * 
     * @remark 根据底层界面的状态赋相应的类型值
     */
    private void setNullCurChapterType() {
        // throw new IllegalArgumentException("mBookContentInfo.getCurChapterType() is null");
        if (mBookContentInfo.getType() == Constant.BOOKTYPE_PAY) {
            mBookContentInfo.setCurChapterType(BookContentUtils.TYPE_HAS_READ);
        } else if (mBookContentInfo.getType() == Constant.BOOKTYPE_ORDER_PAY) {
            mBookContentInfo.setCurChapterType(BookContentUtils.TYPE_NEDD_BUY);
        }
        // Log4an.e("yjd", "isStatusListenerValid()=" + isStatusListenerValid());
        // if (isStatusListenerValid()) {
        // mStatusListener.get().onShowMsg(R.string.getchapter_fail);
        // mStatusListener.get().onLoadFailed(null);
        // }
    }

    private void updateNextChapter() {
        // Log4an.i(
        // "draw",
        // "【updateNextChapter】" + ",isResetNextIndex="
        // + mBookContentRender.isResetNextIndex());
        if (mBookContentRender.isResetNextIndex() == 1) {
            BookContentLocalAppTXTParser.change = true;
            mBookContentParserBase.hasNextChapter(mBookContentRender.getFirstByteIndex());
        }
        mBookContentParserBase.getCurInfos(ShuqiApplication.getContext(), mBookContentInfo, true);
        BookContentLocalAppTXTParser.change = false;
        mBookContentInfo.resetPayType();
        // Log4an.i("draw", "【updateNextChapter】isNetBook()=" + isNetBook() + ",type="
        // + mBookContentInfo.getType() + ",isJumpChapter=" + isJumpChapter());
        if (isNetBook()) {
            // Log4an.i("draw",
            // "mBookContentInfo.getCurChapterType()=" + mBookContentInfo.getCurChapterType());
            if (TextUtils.isEmpty(mBookContentInfo.getCurChapterType())) {
                setNullCurChapterType();
            }
            if (BookContentUtils.TYPE_HAS_READ.equals(mBookContentInfo.getCurChapterType())) {
                resetChapterNormal();
                mBookContentInfo.refreshCurChapterContentLines(mBookContentRender,
                        mBookContentInfo.getMarkIndex());
                mBookContentInfo.setCurChapterLineIndex(0);
            } else if (BookContentUtils.TYPE_DOWN_FAIL.equals(mBookContentInfo.getCurChapterType())) {
                setTypeDonwload(
                        TextUtils.isEmpty(mBookContentInfo.getCurChapterName()) ? mBookContentInfo.getBookname()
                                : mBookContentInfo.getCurChapterName(), 6);
            } else if (BookContentUtils.TYPE_NO_NET.equals(mBookContentInfo.getCurChapterType())) {
                setTypeDonwload(
                        TextUtils.isEmpty(mBookContentInfo.getCurChapterName()) ? mBookContentInfo.getBookname()
                                : mBookContentInfo.getCurChapterName(), 1);
            } else if (BookContentUtils.TYPE_GET_CATALOG_FAIL.equals(mBookContentInfo
                    .getCurChapterType())) {
                setTypeDonwload(
                        TextUtils.isEmpty(mBookContentInfo.getCurChapterName()) ? mBookContentInfo.getBookname()
                                : mBookContentInfo.getCurChapterName(), 5);
            } else {
                resetChapterPay();
            }
        } else {
            resetChapterNormal();
            mBookContentInfo.refreshCurChapterContentLines(mBookContentRender,
                    mBookContentInfo.getMarkIndex());
            mBookContentInfo.setCurChapterLineIndex(0);
        }
    }

    /***
     * 是否为网络图书
     * 
     * @return
     */
    private boolean isNetBook() {
        return Constant.BOOKTYPE_PAY == mBookContentInfo.getType()
                || Constant.BOOKTYPE_NET == mBookContentInfo.getType()
                || Constant.BOOKTYPE_ORDER_PAY == mBookContentInfo.getType();
    }

    public int loadPrevNormalPage() {
        mBookContentInfo.setCurChapterLineIndex(mBookContentRender.getFirstLineIndex());
        mBookContentInfo.setCurSreenLineCount(mBookContentRender.getCurLineNum()
                - mBookContentRender.getTagCount());
//        Log4an.i("draw",
//                "【loadPrevNormalPage】curLineIndex=" + mBookContentInfo.getCurChapterLineIndex()
//                        + ",CurSreenLineCount=" + mBookContentInfo.getCurSreenLineCount()
//                        + ",curLineNum=" + mBookContentRender.getCurLineNum() + ",tagCount="
//                        + mBookContentRender.getTagCount());
        if (mBookContentInfo.hasNotPrevPage(mBookContentParserBase)) {
            if (isStatusListenerValid()) {
                mStatusListener.get().onShowMsg(R.string.unfind_pre_chapter);
            }
            return BookContentView.DIRECTION_OTHER;
        }
        moveToNomalPrevPage();
        // 更新画面picture
        refreshView(false);

        return BookContentView.DIRECTION_RIGHT;
    }


    public void saveBookMark() {
        mBookContentInfo.setCurChapterLineIndex(mBookContentRender.getFirstLineIndex());
        mBookContentInfo.resetCurChapterOffestIndex();
        BookContentUtils.saveBookMark(mBookContentInfo);
        Log4an.i("yjd", "【wifi进入阅读页】bid=" + mBookContentInfo.getBookId() + ",uid="
                + mBookContentInfo.getUid() + ",sourceID=" + mBookContentInfo.getSourceId());
        SharedPreferenceUtil.deleteWifiTemp(mContext, mBookContentInfo.getBookId(),
                mBookContentInfo.getUid(), mBookContentInfo.getSourceId());
    }

    public BookInfo resetBookInfo(boolean isRefresh) {
        if (mBookInfo == null || isRefresh) {
            mBookInfo =
                    BookInfoDao.getInstance().getBookInfo(mBookContentInfo.getSourceId(),
                            mBookContentInfo.getBookId(), mUserInfo.getUserId());
        }
        // Log4an.e("yjd", "【BookInfo】mBookInfo is null=" + (mBookInfo == null ? true : false));
        if (mBookInfo != null) {
            // Log4an.e(
            // "yjd",
            // "【BookInfo】书名=" + mBookInfo.getBookName() + ",bid=" + mBookInfo.getBookId()
            // + ",maxOid=" + mBookInfo.getBookMaxOid() + "作者："
            // + mBookInfo.getBookAuthorName());
            mBookContentInfo.setBookname(mBookInfo.getBookName());
            mBookContentInfo.setAuthor(mBookInfo.getBookAuthorName());
            mBookContentInfo.setTotalLength(mBookInfo.getBookMaxOid());
            mBookContentInfo.setBookInfo(mBookInfo);
            mBookContentInfo.setImageUrl(mBookInfo.getBookCoverImgUrl());
        }
        return mBookInfo;
    }

    private boolean isValidBookInfo(BookContentInfo bookContentInfo) {
        return bookContentInfo != null;
    }

    @Override
    public void loadBookContentInfoCompleted() {
        postTaskToUiThread(new Runnable() {
            @Override
            public void run() {
                loadCurPage();
            }
        });
    }

    @Override
    public void controlBuyButtonIsClick(boolean isClick) {
        if (isClick) {
            blockBookContentView(!mBookContentMenuView.isMenuEnable());
            if (isStatusListenerValid()) {
                mStatusListener.get().onNeedBuyStatusChanged(true);
                if (!mBookContentMenuView.isMenuEnable()) {
                    mStatusListener.get().onLoadingStatusChanged(false, false);
                }
            }
        } else {
            if (isStatusListenerValid()) {
                mStatusListener.get().onNeedBuyStatusChanged(false);
            }
        }
    }

    @Override
    public void hideBuyLoadingDialog() {
        if (isStatusListenerValid()) {
            mStatusListener.get().onBuyLoadingStatusChanged(false);
        }
    }

    @Override
    public void onAutoBuy() {
        blockBookContentView(true);
        if (isStatusListenerValid()) {
            mStatusListener.get().onNeedBuyStatusChanged(false);
            mStatusListener.get().onLoadingStatusChanged(false, false);
            mStatusListener.get().onBuyLoadingStatusChanged(true);
        }
    }

    @Override
    public void onPayCataLogData(BookData catalog, int pageCount) {
        mCataLogLayout.initPayCataLog(catalog, pageCount);
    }

    @Override
    public void onCataLogScan(CataLogLayout.OnCatalogScanListener listener) {
        mCataLogLayout.cataLogScan(mBookContentInfo.getType(), mBookContentInfo.getFliePath(),
                mBookContentInfo.getBookId(), mUserInfo.getUserId(),
                mBookContentInfo.getCurChapterCid(), mBookContentInfo.getUid(),
                mBookContentInfo.getSourceId(), listener);
    }

    @Override
    public void onResetPageIndex() {
        mBookContentInfo.setCurChapterLineIndex(0);
    }

    @Override
    public List<BookContentLineInfo> getPreLines() {
        return mBookContentInfo.getPrevChapter().getContentLines();
    }

    @Override
    public List<BookContentLineInfo> getCurLines() {
        return mBookContentInfo.getCurChapter().getContentLines();
    }

    @Override
    public List<BookContentLineInfo> getNextLines() {
        return mBookContentInfo.getNextChapter().getContentLines();
    }

    @Override
    public int getLineIndex() {
        return mBookContentInfo.getCurChapterLineIndex();
    }

    @Override
    public int getLinesNum() {
        return mBookContentInfo.getCurSreenLineCount();
    }

    @Override
    public int getBookType() {
        return mBookContentInfo.getType();
    }

    /**
     * 根据progress拿到当前的章节名
     */
    public void showCharpterName(float progress) {
        if (mBookContentInfo.getType() == Constant.BOOKTYPE_TXT) {// 杀手总裁的出逃妻 为空 测试注意
            int seekIndex = (int) (mBookContentInfo.getTotalLength() * progress);
            seekIndex = Math.min(mBookContentInfo.getTotalLength() - 12, seekIndex);
            seekIndex = seekIndex / 2 * 2;
            mBookContentInfo.setStartIndex(seekIndex);
            mBookContentInfo.setEndIndex(seekIndex + Constant.READ_BYTEBUFFER_LENTH);
            /*
             * mBookContentParserBase.getCurInfos(ShuqiApplication.getContext(),
             * mBookContentInfo,true); mBookContentMenuView.showCharpter(progress,
             * mBookContentInfo.getCurChapterName());
             */
            BookContentInfo info =
                    mBookContentParserBase.getCurCharpterNameFromProgress(
                            ShuqiApplication.getContext(), mBookContentInfo);
            mBookContentMenuView.showCharpter(progress, info.getCurChapterName());

        } else if (mBookContentInfo.getType() == Constant.BOOKTYPE_UMD) {

            int seekIndex = (int) (mBookContentInfo.getTotalLength() * progress);
            seekIndex = Math.min(mBookContentInfo.getTotalLength() - 12, seekIndex);
            seekIndex = seekIndex / 2 * 2;
            mBookContentInfo.setStartIndex(seekIndex);
            mBookContentParserBase.getCurInfos(ShuqiApplication.getContext(), mBookContentInfo,
                    true);
            mBookContentMenuView.showCharpter(progress, mBookContentInfo.getCurChapterName());

        } else if (mBookContentInfo.getType() == Constant.BOOKTYPE_EPUB) {

            int curChapterId = Math.round(mBookContentInfo.getTotalLength() * progress);
            curChapterId = Math.max(0, curChapterId - 1);
            mBookContentInfo.setCurChapterCid(String.valueOf(curChapterId));
            // mBookContentParserBase.getCurInfos(mContext, mBookContentInfo, true);
            // mBookContentMenuView.showCharpter(progress, mBookContentInfo.getCurChapterName());
            BookContentInfo info =
                    mBookContentParserBase.getCurCharpterNameFromProgress(mContext,
                            mBookContentInfo);
            mBookContentMenuView.showCharpter(progress, info.getCurChapterName());

        } else if (mBookContentInfo.getType() == Constant.BOOKTYPE_BAG) {

            int position = Math.round(mBookContentInfo.getTotalLength() * progress);
            mBookContentInfo.setCurChapterCid(String.valueOf(mBookContentParserBase
                    .getChapterId(position)));
            // mBookContentParserBase.getCurInfos(mContext, mBookContentInfo, true);
            // mBookContentMenuView.showCharpter(progress, mBookContentInfo.getCurChapterName());
            BookContentInfo info =
                    mBookContentParserBase.getCurCharpterNameFromProgress(mContext,
                            mBookContentInfo);
            mBookContentMenuView.showCharpter(progress, info.getCurChapterName());

        } else {
            if (mBookInfo != null) {
                int mOid = Math.max((int) (progress * mBookInfo.getBookMaxOid()), 1);
                BookCataLog catalogInfo =
                        BookCataLogDao.getInstance().getBookCatalogByChapterIndex(
                                mBookContentInfo.getUid(), mBookContentInfo.getBookId(),
                                mBookContentInfo.getSourceId(), mOid);

                mBookContentMenuView.showCharpter(progress,
                        catalogInfo == null ? "" : catalogInfo.getChapterName());
            }
        }
    }

    public void doJumpSeeked(float progress) {
        if (!verifyMenuOptionAvailability())
            return;
        if (isLoading()) {
            return;
        } else {
            setIsLoading(true);
        }
        resetFirstLineStartByteIndexBeforeSettingChanged();
        // Log4an.i("yjd", "[doJumpSeeked]mBookContentInfo.getType()=" +
        // mBookContentInfo.getType());
        setClickMenuJumpChapter(true);
        if (mBookContentInfo.getType() == Constant.BOOKTYPE_TXT) {
            // Log4an.e("yjd", "【doJumpSeeked】文件大小=" + mBookContentInfo.getTotalLength()
            // + ",progress=" + progress);
            int seekIndex = (int) (mBookContentInfo.getTotalLength() * progress);
            // Log4an.e("yjd", "1.seekIndex=" + seekIndex);
            seekIndex = Math.min(mBookContentInfo.getTotalLength() - 12, seekIndex);
            // Log4an.e("yjd", "2.seekIndex=" + seekIndex);
            seekIndex = seekIndex / 2 * 2;
            // Log4an.e("yjd", "最终seekIndex=" + seekIndex);
            mBookContentInfo.setStartIndex(seekIndex);
            mBookContentInfo.setEndIndex(seekIndex + Constant.READ_BYTEBUFFER_LENTH);
            // Log4an.e("yjd", "start=" + mBookContentInfo.getStartIndex() + ",end="
            // + mBookContentInfo.getEndIndex());
            blockBookContentView(false);
            loadLocalBookData();
            setIsLoading(false);
        } else if (mBookContentInfo.getType() == Constant.BOOKTYPE_UMD) {
            int seekIndex = (int) (mBookContentInfo.getTotalLength() * progress);
            // Log4an.e(
            // "yjd",
            // "【doJumpSeeked】progress=" + progress + ",文件大小="
            // + mBookContentInfo.getTotalLength() + ",seekIndex=" + seekIndex);
            if (seekIndex >= mBookContentInfo.getTotalLength()) {
                seekIndex = mBookContentInfo.getTotalLength() - 100;
                // Log4an.e("yjd", "经过处理后的seekIndex=" + seekIndex);
            } else {
                seekIndex = Math.min(mBookContentInfo.getTotalLength() - 12, seekIndex);
                // Log4an.e("yjd", "经过最小运算后seekIndex=" + seekIndex);
                seekIndex = seekIndex / 2 * 2;

            }
            // Log4an.e("yjd", "最终seekIndex=" + seekIndex);
            mBookContentInfo.setStartIndex(seekIndex);
            blockBookContentView(false);
            loadLocalBookData();
            setIsLoading(false);
        } else if (mBookContentInfo.getType() == Constant.BOOKTYPE_EPUB) {
            int curChapterId = Math.round(mBookContentInfo.getTotalLength() * progress);
            curChapterId = Math.max(0, curChapterId - 1);
            mBookContentInfo.setCurChapterCid(String.valueOf(curChapterId));
            mBookContentParserBase.getCurInfos(mContext, mBookContentInfo, true);
            mBookContentInfo.refreshCurChapterContentLines(mBookContentRender,
                    mBookContentInfo.getMarkIndex());
            mBookContentInfo.setCurChapterLineIndex(0);
            loadCurPage();
            setIsLoading(false);
        } else if (mBookContentInfo.getType() == Constant.BOOKTYPE_BAG) {
            // Log4an.e("yjd", "【bag】totalLen=" + mBookContentInfo.getTotalLength() + ",progress="
            // + progress);
            int position = Math.round(mBookContentInfo.getTotalLength() * progress);
            // Log4an.e("yjd", "【bag】position=" + position);
            mBookContentInfo.setCurChapterCid(String.valueOf(mBookContentParserBase
                    .getChapterId(position)));
            // Log4an.e("yjd", "【bag】curCid=" + mBookContentInfo.getCurChapterCid());
            mBookContentParserBase.getCurInfos(mContext, mBookContentInfo, true);
            mBookContentInfo.refreshCurChapterContentLines(mBookContentRender,
                    mBookContentInfo.getMarkIndex());
            mBookContentInfo.setCurChapterLineIndex(0);
            loadCurPage();
            setIsLoading(false);
        } else {
            if (mBookInfo != null) {
                int mOid = Math.max((int) (progress * mBookInfo.getBookMaxOid()), 1);
                // Log4an.e("liyizhe", "jump:OID=" + mOid + ",progress=" + progress + ",maxOID="
                // + mBookInfo.getBookMaxOid());
                BookCataLog catalogInfo =
                        BookCataLogDao.getInstance().getBookCatalogByChapterIndex(
                                mBookContentInfo.getUid(), mBookContentInfo.getBookId(),
                                mBookContentInfo.getSourceId(), mOid);
                doJumpChapter(catalogInfo);
            }
        }
    }

    private void doJumpChapter(BookCataLog catalogInfo) {
        if (catalogInfo != null) {
            verifyLoadingProgressDialog(mBookContentInfo.getBookId(),
                    mBookContentInfo.getSourceId(), catalogInfo.getChapterId(),
                    mBookContentInfo.getUid(), String.valueOf(catalogInfo.getPayMode()));
            setJumpChapter(true);
            mBookContentInfo.turnToChapter(catalogInfo);
            reloadCurChapter();
            refreshView(false);
            setJumpChapter(false);
        }
    }

    public void doJumpPrevChapter() {
        if (!verifyMenuOptionAvailability())
            return;
        if (isLoading()) {
            return;
        } else {
            setIsLoading(true);
        }
        resetFirstLineStartByteIndexBeforeSettingChanged();
        if (mBookContentInfo.getType() == Constant.BOOKTYPE_TXT
                || mBookContentInfo.getType() == Constant.BOOKTYPE_UMD) {
            if (!mBookContentInfo.getCurChapter().isValid()) {
                setIsLoading(false);
                return;
            }
            List<BookContentInfo> catalogList = mCataLogLayout.getLocalCatalogList();
            BookContentLineInfo lineInfo =
                    mBookContentInfo.getCurChapterContentLines().get(
                            mBookContentInfo.getCurChapterLineIndex());
            if (catalogList == null || catalogList.size() == 0) {
                if (isStatusListenerValid()) {
                    mStatusListener.get().onShowMsg(R.string.unfind_chapter);
                }
                setIsLoading(false);
                return;
            } else if ((lineInfo.getFirstIndex() - 1) < catalogList.get(0).getStartIndex()) {
                if (isStatusListenerValid()) {
                    mStatusListener.get().onShowMsg(R.string.unfind_pre_chapter);
                }
                setIsLoading(false);
                return;
            }
            setClickMenuJumpChapter(true);
            BookContentUtils.calcLocalBookPrevChapterStartIndex(mBookContentInfo, lineInfo,
                    catalogList);
            loadLocalBookData();
        } else {
            onJumpChapter(false);
        }
        StatisticsUtils.onEvent(StatisticsEventID.BOOKCONTENT_PRE_CHAPTER);
        setIsLoading(false);
    }

    /** 是否是跳章(true:跳到章节首页;false:不按照章节跳) */
    private boolean isJumpChapter = false;
    /** 是否要刷新当前页首行索引(异常情况进入正文) */
    private boolean isRefreshIndex = false;

    /**
     * @return the isRefreshIndex
     */
    public boolean isRefreshIndex() {
        return isRefreshIndex;
    }

    /**
     * @param isRefreshIndex the isRefreshIndex to set
     */
    public void setRefreshIndex(boolean isRefreshIndex) {
        this.isRefreshIndex = isRefreshIndex;
    }

    /**
     * @param isJumpChapter the isJumpChapter to set
     */
    public void setJumpChapter(boolean isJumpChapter) {
        this.isJumpChapter = isJumpChapter;
    }



    /**
     * @return the isJumpChapter
     */
    public boolean isJumpChapter() {
        return isJumpChapter;
    }

    private void loadLocalBookData() {
        setJumpChapter(true);
        mBookContentInfo.setMarkIndex(0);
        mBookContentParserBase.getCurInfos(ShuqiApplication.getContext(), mBookContentInfo, true);
        mBookContentInfo.refreshCurChapterContentLines(mBookContentRender,
                mBookContentInfo.getMarkIndex());
        mBookContentInfo.setCurChapterLineIndex(0);
        setIsLoading(false);
        blockBookContentView(false);
        refreshView(false);
        setJumpChapter(false);
    }

    /** 当点击菜单上下章节按钮时，改变此状态，按跳章逻辑处理绘制层 */
    private boolean isClickMenuJumpChapter = false;

    /**
     * @return the isClickMenuJumpChapter
     */
    public boolean isClickMenuJumpChapter() {
        return isClickMenuJumpChapter;
    }

    /**
     * @param isClickMenuJumpChapter the isClickMenuJumpChapter to set
     */
    public void setClickMenuJumpChapter(boolean isClickMenuJumpChapter) {
        this.isClickMenuJumpChapter = isClickMenuJumpChapter;
    }

    public void doJumpNextChapter() {
        if (!verifyMenuOptionAvailability())
            return;
        if (isLoading()) {
            return;
        } else {
            setIsLoading(true);
        }
        resetFirstLineStartByteIndexBeforeSettingChanged();
        if (mBookContentInfo.getType() == Constant.BOOKTYPE_TXT
                || mBookContentInfo.getType() == Constant.BOOKTYPE_UMD) {

            List<BookContentInfo> catalogList = mCataLogLayout.getLocalCatalogList();
            // Log4an.i("yjd", "【上下章节】catalogList is null="
            // + (catalogList == null ? true : catalogList.size()) + ",lineIndex="
            // + mBookContentInfo.getCurChapterLineIndex());
            BookContentLineInfo lineInfo =
                    mBookContentInfo.getCurChapterContentLines().get(
                            mBookContentInfo.getCurChapterLineIndex());

            // Log4an.i("yjd", "getFirstIndex=" + lineInfo.getFirstIndex());
            if (catalogList == null || catalogList.size() == 0) {
                if (isStatusListenerValid()) {
                    mStatusListener.get().onShowMsg(R.string.unfind_chapter);
                }
                setIsLoading(false);
                return;
            } else if (lineInfo.getFirstIndex() >= catalogList.get(catalogList.size() - 1)
                    .getStartIndex()) {
                if (isStatusListenerValid()) {
                    mStatusListener.get().onShowMsg(R.string.unfind_next_chapter);
                }
                setIsLoading(false);
                return;
            }
            setClickMenuJumpChapter(true);
            BookContentUtils.calcLocalBookNextChapterStartIndex(mBookContentInfo, lineInfo,
                    catalogList);
            loadLocalBookData();
        } else {
            onJumpChapter(true);
        }
        StatisticsUtils.onEvent(StatisticsEventID.BOOKCONTENT_NEXT_CHAPTER);
        setIsLoading(false);
    }

    /**
     * 设置目录布局是否可具有焦点
     * 
     * @param isClick
     */
    public void setCatalogLayout(boolean isClick) {
        mCataLogLayout.setClickable(isClick);
        mCataLogLayout.setFocusable(isClick);
        mCataLogLayout.setFocusableInTouchMode(isClick);
    }

    public void doNavigateToCatalog() {
        // Log4an.i("yjd", "【doNavigateToCatalog】getBookType()=" + getBookType());
        if (getBookType() == Constant.BOOKTYPE_NET) {
            String url =
                    Urls.getWebBookCatalogUrl(mContext, mBookContentInfo.getBookId(),
                            mBookContentInfo.getSourceId());
            mStatusListener.get().onOpenWebkit(url);
        } else {
            blockBookContentView(false);
            // Log4an.i("yjd",
            // "mBookContentView.getViewEnabled()=" + mBookContentView.getViewEnabled());
            if (!mBookContentView.getViewEnabled()) {
                setCatalogLayout(true);
            }
            synchronized (this.getClass()) {
                mCataLogLayout.open(mBookContentInfo.getType(), mBookContentInfo.getBookname(),
                        mBookContentInfo.getTotalLength(),
                        mBookContentInfo.getCurChapterContentLines(),
                        mBookContentInfo.getCurChapterLineIndex(),
                        mBookContentInfo.getCurChapterCid(),
                        mBookContentParserBase.getBookCatalogList());
            }
        }
    }

    /**
     * 获取目录数据 by Linyuren
     * */
    public void doOnlyGetCatalogData() {
        synchronized (this.getClass()) {
            mCataLogLayout.onleGetCalotyData(mBookContentInfo.getType(),
                    mBookContentParserBase.getBookCatalogList());
        }
    }

    /**
     * 收费版跳转上、下章节内容
     * 
     * @param isNext
     */
    private void onJumpChapter(boolean isNext) {

        boolean lastBookType =
                Constant.BOOKTYPE_PAY == mBookContentInfo.getType()
                        || Constant.BOOKTYPE_ORDER_PAY == mBookContentInfo.getType();

        if (isNext) {
            // Log4an.e("yyy", "nextCid=" + mBookContentInfo.getNextChapterCid() + ",curCid="
            // + mBookContentInfo.getCurChapterCid());
            if (TextUtils.isEmpty(mBookContentInfo.getNextChapterCid())) {
                if (isStatusListenerValid()) {
                    mStatusListener.get().onShowMsg(R.string.unfind_next_chapter);
                }
                return;
            }

            /** 付费和epub的不需要穿index来判断是 */
            if (!mBookContentParserBase.hasNextChapter(-1)) {
                notifyHasNoNextChapterToast();
                return;
            }
            setClickMenuJumpChapter(true);
            verifyLoadingProgressDialog(mBookContentInfo.getBookId(),
                    mBookContentInfo.getSourceId(), mBookContentInfo.getNextChapterCid(),
                    mBookContentInfo.getUid(), mBookContentInfo.getNextChapterPayMode());
            mBookContentInfo.turnNextChapter(mBookContentParserBase, mBookContentRender);
        } else {
            // Log4an.e("yyy", "preCid=" + mBookContentInfo.getPreChapterCid() + ",curCid="
            // + mBookContentInfo.getCurChapterCid());
            if (TextUtils.isEmpty(mBookContentInfo.getPreChapterCid())) {
                if (isStatusListenerValid()) {
                    mStatusListener.get().onShowMsg(R.string.unfind_pre_chapter);
                }
                return;
            }
            setClickMenuJumpChapter(true);
            // Log4an.e("yyy", "*********************");
            verifyLoadingProgressDialog(mBookContentInfo.getBookId(),
                    mBookContentInfo.getSourceId(), mBookContentInfo.getPreChapterCid(),
                    mBookContentInfo.getUid(), mBookContentInfo.getPreChapterPayMode());
            mBookContentInfo.turnPrevChapter(mBookContentParserBase, mBookContentRender);
        }

        if (lastBookType
                && BookContentUtils.TYPE_HAS_READ.equals(mBookContentInfo.getCurChapterType())) {
            notifyCatalogLayoutPayState();
        }

        if (isNetBook()) {
            if (TextUtils.isEmpty(mBookContentInfo.getCurChapterType())) {
                setNullCurChapterType();
            }

            // Log.d(TAG,
            // "mBookContentInfo.getCurChapterType() :　"
            // + mBookContentInfo.getCurChapterType());

            if (BookContentUtils.TYPE_HAS_READ.equals(mBookContentInfo.getCurChapterType())) {
                resetChapterNormal();
            } else if (BookContentUtils.TYPE_DOWN_FAIL.equals(mBookContentInfo.getCurChapterType())) {
                setTypeDonwload(mBookContentInfo.getCurChapterName(), 6);
            } else if (BookContentUtils.TYPE_NO_NET.equals(mBookContentInfo.getCurChapterType())) {
                setTypeDonwload(
                        TextUtils.isEmpty(mBookContentInfo.getCurChapterName()) ? mBookContentInfo.getBookname()
                                : mBookContentInfo.getCurChapterName(), 1);
            } else if (BookContentUtils.TYPE_GET_CATALOG_FAIL.equals(mBookContentInfo
                    .getCurChapterType())) {
                setTypeDonwload(
                        TextUtils.isEmpty(mBookContentInfo.getCurChapterName()) ? mBookContentInfo.getBookname()
                                : mBookContentInfo.getCurChapterName(), 5);
            } else {
                resetChapterPay();
            }
        }
        setIsLoading(false);
        refreshView(isNext);
    }

    /**
     * 检查是否需要显示Loading滚动条
     */
    private void verifyLoadingProgressDialog(String bookId, String sourceId, String chapterId,
            String uId, String chapterPayMode) {
        if (mBookContentParserBase.hasLocalCachedData(bookId, sourceId, chapterId, uId) == false
                && BookContentUtils.getIsNeedBuy(mContext, mBookContentInfo, chapterId,
                        chapterPayMode) == false && isStatusListenerValid()) {
            mStatusListener.get().onLoadingStatusChanged(true, false);
        }
    }

    private void resetChapterNormal() {
        mReadState = BookContentModel.READ_STATE_NORMAL;
        if (Constant.BOOKTYPE_ORDER_PAY == mBookContentInfo.getType())
            mBookContentInfo.setType(Constant.BOOKTYPE_PAY);
        if (isStatusListenerValid()) {
            mStatusListener.get().onNeedBuyStatusChanged(false);
        }
    }

    // 显示收费书籍的百分比
    private void showNetPercent(BookContentInfo curChapter, BookInfo bookInfo) {
        // Log4an.i("showNetPercent", "curChapter is null=" + (curChapter == null ? true : false));
        if (curChapter == null) {
            mBookContentBottomView.resetReadPercent(0);
            mBookContentInfo.setPercent1(String.valueOf(0));
            return;
        }
        float per = 0.00f;
        // 计算收费版百分比
        BookCataLog catalogInfo =
                BookCataLogDao.getInstance().getBookCatalogByCid(mBookContentInfo.getUid(),
                        mBookContentInfo.getBookId(), mBookContentInfo.getSourceId(),
                        curChapter.getCurChapterCid());
        int curChapterSize = 0;
        if (catalogInfo != null) {
            curChapterSize = catalogInfo.getOId();
        }
        int totalChapter = 0;
        if (bookInfo != null) {
            totalChapter = bookInfo.getBookMaxOid();
        } else {
            resetBookInfo(true);
            if (mBookInfo != null) {
                totalChapter = mBookInfo.getBookMaxOid();
            }
        }
        if (totalChapter > 0) {
            per = Float.valueOf(curChapterSize) / totalChapter;
            per = per > 1 ? 1 : per;
            // Log4an.i("showNetPercent", "per=" + per);
            mBookContentBottomView.resetReadPercent(per);
            mBookContentInfo.setPercent1(String.valueOf(per * 100));
        }
    }

    /**
     * 获取已读的百分比
     */
    public float getReadedProgress() {
        if (mBookContentInfo == null) {
            return 0;
        }
        if (mBookContentInfo.getType() == Constant.BOOKTYPE_BAG) {
            int position = mBookContentParserBase.getPostion(mBookContentInfo.getCurChapterCid());
            float percent =
                    BookContentUtils.getChapterPercent(position, mBookContentInfo.getTotalLength());
            if (percent > 1) {
                percent = 1;
            }
            return percent;
        }
        return mBookContentInfo.getReadedProgress();
    }

    /**
     * 显示阅读百分比进度
     * 
     * @param isNext : true下一页；false上一页
     */
    private void showPercent(boolean isNext, int type, BookContentInfo curChapter,
            BookInfo bookInfo, List<BookContentLineInfo> curLines, int lineIndex, int linesNum) {

        // Log4an.e(TAG_SHOW_PERENT, "【showPercent】isNext="
        // + isNext
        // + ",type="
        // + type
        // + ",curLines is null="
        // + (curLines == null ? true : curLines.size() + ",lineIndex=" + lineIndex
        // + ",linesNum=" + linesNum));
        if (type == Constant.BOOKTYPE_PAY || type == Constant.BOOKTYPE_ORDER_PAY
                || type == Constant.BOOKTYPE_NET) {
            showNetPercent(curChapter, bookInfo);
        } else if (type == Constant.BOOKTYPE_EPUB) {
            final float per = mBookContentInfo.getReadedProgress();
            mBookContentInfo.setPercent1(String.valueOf(per));
            mBookContentBottomView.resetReadPercent(per);
        } else if (type == Constant.BOOKTYPE_BAG) {
            showBookBagPercent();
        } else {
            float percent = mBookContentInfo.getReadedProgress();
            // Log4an.e(TAG_SHOW_PERENT, "percent=" + percent);
            percent = percent >= 1.0f ? 1.0f : percent;
            mBookContentInfo.setPercent1(String.valueOf(percent));
            mBookContentBottomView.resetReadPercent(percent);
        }
    }

    /**
     * 显示书包的百分比
     */
    private void showBookBagPercent() {
        float percent = getReadedProgress();
        mBookContentInfo.setPercent1(String.valueOf(percent));
        mBookContentBottomView.resetReadPercent(percent);
    }

    private void showPercent(final boolean isNext) {
        postTaskToUiThread(new Runnable() {
            @Override
            public void run() {
                mBookContentInfo.setCurChapterLineIndex(mBookContentRender.getFirstLineIndex());
                mBookContentInfo.setCurSreenLineCount(mBookContentRender.getCurLineNum());
                showPercent(isNext, mBookContentInfo.getType(), mBookContentInfo, mBookInfo,
                        mBookContentInfo.getCurChapterContentLines(),
                        mBookContentInfo.getCurChapterLineIndex(),
                        mBookContentInfo.getCurSreenLineCount());
            }
        });
    }

    public void loadCurPage() {

        initCanvas();

        // Log.d(TAG, "loadCurPage mReadState : " + mReadState);

        // 通知自定义View可用
        // setIsLoading(false);
        openSetIsLoading(false);
        blockBookContentView(true);
        showTopTitle();
        notifyUpdateDataChanged(true);
        showPercent(false);

        // if (isStatusListenerValid()) {
        // mStatusListener.get().onLoadingStatusChanged(false);
        // }
        if (isStatusListenerValid()) {
            mStatusListener.get().onOpenLoadingStatusChanged(false);
        }
    }

    /***
     * 获得章节目录信息
     */
    public void cataLogScan() {
        mCataLogLayout.cataLogScan(mBookContentInfo.getType(), mBookContentInfo.getFliePath(),
                mBookContentInfo.getBookId(), mUserInfo.getUserId(),
                mBookContentInfo.getCurChapterCid(), mBookContentInfo.getUid(),
                mBookContentInfo.getSourceId(), null);
    }

    private String getTheSourceLink() {
        return mCataLogLayout.getTheSourceLink(mBookContentInfo.getUid(),
                mBookContentInfo.getSourceId(), mBookContentInfo.getBookId(),
                mBookContentInfo.getCurChapterCid());
    }

    /**
     * 按章购买
     * 
     * @param chapterInfo
     * @return
     */
    public int refreshPage(ChapterInfo chapterInfo, boolean isShowDialog) {
        resetBookContentInfo(chapterInfo);
        reloadCurChapter();

        notifyCatalogLayoutPayState();

        if (isStatusListenerValid()) {
            mStatusListener.get().onReturnFinish();
            mStatusListener.get().onBuySuccessed(isShowDialog);
        }
        return BookContentView.DIRECTION_OTHER;
    }

    public void reloadCurChapter() {
        processMoveToNextChapterOption();
        setIsLoading(false);
        onAnimationFinished();
        refreshView(true);
    }

    private void resetBookContentInfo(ChapterInfo bookInfo) {
        mBookContentInfo.setCurChapterName(mBookContentInfo.getCurChapterName());
        mBookContentInfo.setBookId(bookInfo.getBookId());
        mBookContentInfo.setCurChapterCid(bookInfo.getCurChapterCid());
        mBookContentInfo.setCurChapterPayMode("0");// curChapter.getNextChapterPayMode()
        mBookContentInfo.setNeedBuy(getNeedBuyState());
        mBookContentInfo.setType(Constant.BOOKTYPE_PAY);
        mBookContentInfo.setCurChapterType(BookContentUtils.TYPE_HAS_READ);
    }

    public void onMenuKeyDown() {
        if (mBookContentMenuView.getVisibility() == View.VISIBLE) {
            mBookContentMenuView.setVisibility(View.GONE, true, mBookContentMenuView.mWhich);
            blockBookContentView(true);
            mBookContentMenuView.setMenuEnable(false);// 菜单消失，不可用
        } else {
            if ((mBookContentInfo.getType() == Constant.BOOKTYPE_PAY || mBookContentInfo.getType() == Constant.BOOKTYPE_ORDER_PAY)
                    && mBookContentInfo.getTotalLength() == 0) {
                if (mBookInfo != null)
                    mBookContentInfo.setTotalLength(mBookInfo.getBookMaxOid());
            }
            mBookContentMenuView.mWhich = Constant.MENU_FIRST_LAYOUT;
            mBookContentMenuView.setVisibility(View.VISIBLE, true, mBookContentMenuView.mWhich);
            blockBookContentView(false);
            mBookContentMenuView.setMenuEnable(true);// 菜单出现，可用
            mBookContentView.onResetmScrollDirection();
        }
    }

    public boolean onBackKeyDown() {
        if (mCataLogLayout.close()) {
            return true;
        }
        if (settings.isCopyMode()) {
            onViewCopyModeCompleted();
            return true;
        }
        StatisticsUtils.onEvent(StatisticsEventID.BOOKCONTENT_PHYSICAL_BACK);
        if (mBookContentMenuView.isShown()) {
            mBookContentMenuView.setMenuEnable(false);// 菜单消失，不可用
            blockBookContentView(true);
            mBookContentMenuView.setVisibility(View.GONE, true, mBookContentMenuView.mWhich);
            return true;
        }
        return false;
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
        if (mBookContentInfo.getType() == Constant.BOOKTYPE_PAY
                || mBookContentInfo.getType() == Constant.BOOKTYPE_ORDER_PAY) {
            if (isLoading()) {
                return;
            } else {
                setIsLoading(true);
            }
            blockBookContentView(false);
            mCataLogLayout.close();
            final BookCataLog catalogInfo = mCataLogLayout.getInfoFromCataLog(0, position);
            doJumpChapter(catalogInfo);
            if (mBookContentView.getViewEnabled()) {
                setCatalogLayout(false);
            }
            StatisticsUtils.onEvent(StatisticsEventID.BOOKCONTENT_CATALOG_ENTER_READ);
        } else {
            if (mBookContentInfo.getType() == Constant.BOOKTYPE_TXT) {
                mBookContentInfo.setType(Constant.BOOKTYPE_TXT);
                mBookContentInfo.setFliePath(mBookContentInfo.getFliePath());
                mBookContentInfo.setStartIndex(mCataLogLayout.getStartIndex(position));
                mBookContentInfo.setEndIndex(mCataLogLayout.getEndIndex(position));
            } else if (mBookContentInfo.getType() == Constant.BOOKTYPE_UMD) {
                mBookContentInfo.setType(Constant.BOOKTYPE_UMD);
                mBookContentInfo.setFliePath(mCataLogLayout.getFilePath(position));
                mBookContentInfo.setStartIndex(mCataLogLayout.getStartIndex(position));
            } else if (mBookContentInfo.getType() == Constant.BOOKTYPE_EPUB) {
                mBookContentInfo.setCurChapterCid(String.valueOf(position));
            } else if (mBookContentInfo.getType() == Constant.BOOKTYPE_BAG) {
                mBookContentInfo.setCurChapterCid(mCataLogLayout.getCurChapterId(position));
            }
            resetFirstLineStartByteIndexBeforeSettingChanged();
            loadLocalBookData();
            mCataLogLayout.close();
            if (mBookContentView.getViewEnabled()) {
                setCatalogLayout(false);
            }
            StatisticsUtils.onEvent(StatisticsEventID.BOOKCONTENT_CATALOG_ENTER_READ);
        }
    }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
            int childPosition, long id) {
        // if (mBookContentInfo.getType() == Constant.BOOKTYPE_PAY
        // || mBookContentInfo.getType() == Constant.BOOKTYPE_ORDER_PAY) {
        // if (isLoading()) {
        // return false;
        // } else {
        // setIsLoading(true);
        // }
        // blockBookContentView(false);
        // mCataLogLayout.close();
        // final BookCataLog catalogInfo =
        // mCataLogLayout.getInfoFromCataLog(groupPosition, childPosition);
        // doJumpChapter(catalogInfo);
        // if (mBookContentView.getViewEnabled()) {
        // setCatalogLayout(false);
        // }
        // StatisticsUtils.onEvent(StatisticsEventID.BOOKCONTENT_CATALOG_ENTER_READ);
        // }

        return false;
    }

    public void doLogin() {
        setTypeRequestCode(mBookContentInfo.getCurChapterName());
        notifyUpdateDataChanged(true);
    }


    @Override
    public void OnLeftSliderLayoutStateChanged(boolean bIsOpen) {
        if (bIsOpen) {
            blockBookContentView(false);
        } else {
            blockBookContentView(true);
        }
        if (mBookContentView.getViewEnabled()) {
            setCatalogLayout(false);
        }
    }

    @Override
    public void onResetBookInfo(boolean isReset) {
        resetBookInfo(isReset);
    }

    public interface BookContentModelStatusListener {
        void onLoadingStatusChanged(boolean isLoading, boolean noEnable);

        void onOpenLoadingStatusChanged(boolean isLoading);

        void onShowMsg(int resId);

        void onReadBagEnd(String BookId, String bookName);

        void onNeedBuyStatusChanged(boolean isNeedBuy);

        void onBuySuccessed(boolean isShowDialog);

        void onBuyLoadingStatusChanged(boolean isShow);

        void onLoadFailed(BookContentInfo bookContentInfo);

        void onShowOrigin(String origin);

        void onPostTaskToUiThread(Runnable task);

        void onOpenWebkit(String url);

        /** 判断Activity是否finish */
        void onReturnFinish();

        /** 获取屏幕绘制的行数 */
        int onScreenVisibleLineNum();

        /** 自定义View自由拖动模式时，点击滑动时要滑动的距离 */
        int onViewDistanceInScrollMode();

        /** 设置通知栏高度 */
        void setStatusBarHeight(boolean isSetStatusBarHeight);

        /** 获取通知栏高度 */
        int getStatusBarHeight();
    }

    public synchronized void setOptionsEnable(boolean enable) {
        mIsOptionEnable = mIsOptionEnable;
    }

    private boolean verifyMenuOptionAvailability() {
        if (!mIsOptionEnable && mStatusListener != null && mStatusListener.get() != null) {
            mStatusListener.get().onShowMsg(R.string.bookContentMenuOptionDisable);
        }
        return mIsOptionEnable;
    }

    private boolean isStatusListenerValid() {
        return mStatusListener != null && mStatusListener.get() != null;
    }

    private void postTaskToUiThread(Runnable task) {
        if (isStatusListenerValid()) {
            mStatusListener.get().onPostTaskToUiThread(task);
        }
    }

    @Override
    public void onLoadField(BookContentInfo bookContentInfo) {
        if (isStatusListenerValid()) {
            mStatusListener.get().onLoadFailed(bookContentInfo);
        }
    }

    public String getTxtFilePath() {
        String txtPath = null;
        if (mBookContentInfo.getType() == Constant.BOOKTYPE_TXT) {
            txtPath = mBookContentInfo.getFliePath();
        }
        return txtPath;
    }

    @Override
    public int onViewDistanceInScrollMode() {
        if (isStatusListenerValid()) {
            return mStatusListener.get().onViewDistanceInScrollMode();
        }
        return 0;
    }

    @Override
    public void onViewScroll(float dy) {
        if (dy == 0)
            return;
        mBookContentRender.mScrollOffset += dy;
        int lines =
                (int) (Math.round(mBookContentRender.mScrollOffset) / (BookContentSettings
                        .getInstance(mContext).getTextSize() + BookContentSettings.getInstance(
                        mContext).getLineSpace()));
        int offset =
                (int) (Math.round(mBookContentRender.mScrollOffset) % (BookContentSettings
                        .getInstance(mContext).getTextSize() + BookContentSettings.getInstance(
                        mContext).getLineSpace()));
        mBookContentRender.mScrollOffset = offset;
        int lineIndex = mOnDrawDataListener.getLineIndex();
        lineIndex -= lines;
        mBookContentInfo.setCurChapterLineIndex(lineIndex);
        if (offset > 0) {
            lineIndex--;
            mBookContentInfo.setCurChapterLineIndex(lineIndex);
            mBookContentRender.mScrollOffset =
                    offset
                            - (BookContentSettings.getInstance(mContext).getTextSize() + BookContentSettings
                                    .getInstance(mContext).getLineSpace());
        }
        loadNextPage();
    }

    /** 设置复制模式起始点 */
    public void setStartPoint(float x, float y) {
        if (x < 0 || y < 0)
            return;
        if (startPoint == null) {
            startPoint = new PointF(x, y);
        } else {
            startPoint.set(x, y);
        }
    }

    /** 设置复制模式终点 */
    public void setEndPoint(float x, float y) {
        if (x < 0 || y < 0)
            return;
        if (endPoint == null) {
            endPoint = new PointF(x, y);
        } else {
            endPoint.set(x, y);
        }
    }

    /** 获得自定义PageView的宽度 */
    public int getViewWidth() {
        int width = mBookContentView.getWidth();
        int height = mBookContentView.getHeight();
        if (height == 0) {
            DisplayMetrics dm = new DisplayMetrics();
            ((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);
            height = dm.heightPixels;
        }
        if (SharedPreferenceUtil.getInstanceSharedPreferenceUtil().getBookContentPortraitScreen()) {
            width = Math.min(mBookContentView.mWidth, mBookContentView.mHeight);
        } else {
            width = Math.max(mBookContentView.mWidth, mBookContentView.mHeight);
        }
        return width - mBookContentView.getmSideWidth();
    }

    /** 获得自定义PageView的高度 */
    public int getViewHeight() {
        int width = mBookContentView.getWidth();
        int height = mBookContentView.getHeight();
        if (width == 0) {
            DisplayMetrics dm = new DisplayMetrics();
            ((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);
            width = dm.widthPixels;
            if (!settings.isFullScreen()) {
                width -= mBookContentView.getBarHeight();
            }
        }
        if (height == 0) {
            DisplayMetrics dm = new DisplayMetrics();
            ((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);
            height = dm.heightPixels;
            if (!settings.isFullScreen()) {
                height -= mBookContentView.getBarHeight();
            }
        }
        // true竖屏
        if (SharedPreferenceUtil.getInstanceSharedPreferenceUtil().getBookContentPortraitScreen()) {
            height = Math.max(width, height);
        } else {
            height = Math.min(width, height);
        }
        return height;
    }

    @Override
    public void onViewLongClick(float x, float y) {
        Log4an.i(TAG, "-----x:" + x + "-------------长按阅读页---------y:" + y + "--------");
        // if (!mBookContentView.getViewEnabled() || getCurLines() == null
        // || index + linesNum - 1 <= 0 || index >= getCurLines().size()){
        // Log4an.i(TAG, "复制直接中断了-------");
        // return;
        // }
        if (mReadState != READ_STATE_NORMAL) {
            return;
        }
        index = 20;
        settings.setCopyMode(true);
        // float bottomBarder = settings.getMarginTop() + getLinesNum()
        // * (settings.getTextSize() + settings.getLineSpace()) - settings.getLineSpace()
        // - settings.getTextSize() / 2;

        setStartPoint(x, y);
        setEndPoint(x, y);
        // if (y > bottomBarder) {
        // setStartPoint(x,bottomBarder-settings.getTextSize());
        // setEndPoint(x,bottomBarder);
        // }else{
        // setStartPoint(x, y);
        // setEndPoint(x, y);
        // }

        mBookContentView.initDelayParams();
        if (mBookContentView.getPageTurnMode() == BookContentView.PAGETURN_MODE_SMOOTH) {
            mBookContentRender.mScrollOffset = 0;
            // preparePicture(4, 0);
            drawCopyMode(0, x, y);
        } else {
            mBookContentRender.mScrollOffset = 0;
            // preparePicture(0, 0);
            drawCopyMode(0, x, y);
        }
    }

    /**
     * 画出复制模式
     * 
     * @param handleMode 点击的是哪个手柄
     * @param x 长按那一刻 的x坐标
     * @param y 长按那一刻 的y坐标
     */
    private void drawCopyMode(int handleMode, float longx, float longy) {
        if (getCurLines() == null)
            return;
        int screenWidth = getViewWidth();
        int screenHeight = getViewHeight();
        // 画复制层
        if (settings.isCopyMode()) {
            copyContentList = mBookContentRender.getCopyContentList();
            if (cachePicture == null) {
                cachePicture = mBookContentView.getDefaultPagePicture();
            }
            cachePicture.endRecording();
            Canvas canvas = cachePicture.beginRecording(screenWidth, screenHeight);
            int color = paint.getColor();
            paint.setColor(0x300033ff);

            // TODO ---------判断是否全屏模式 添加title栏高度
            int y;
            y = settings.getMarginTop() + settings.getTopToTitle();
            float p1X = -1, p1Y = -1, p2X = -1, p2Y = -1;
            // 不能超过左边界
            if (endPoint.x <= settings.getMarginLeft()) {
                endPoint.x = settings.getMarginLeft() + 1;
            }
            // 不能超过上边界
            if (startPoint.y < settings.getMarginTop() + settings.getTextSize() / 2) {
                startPoint.y = settings.getMarginTop() + settings.getTextSize() / 2;
            }
            if (endPoint.y < settings.getMarginTop() + settings.getTextSize() / 2) {
                endPoint.y = settings.getMarginTop() + settings.getTextSize() / 2;
            }
            // 不能超过下边界
            int bottomBarder = screenHeight - settings.getMarginBottom();
            if (startPoint.y > bottomBarder) {
                startPoint.y = bottomBarder;
            }
            if (endPoint.y > bottomBarder) {
                endPoint.y = bottomBarder;
            }
            switch (handleMode) {// TODO
                case 1:
                    if (startPoint.y > endPoint.y) {
                        // endPoint.y = startPoint.y;
                        startPoint.y = endPoint.y;
                    }
                    break;
                case 0:
                case 2:
                    if (endPoint.y < startPoint.y) {
                        // startPoint.y = endPoint.y;
                        endPoint.y = startPoint.y;
                    }
                    break;
            }

            // if (startPoint.y > endPoint.y) {
            // startPoint.y = endPoint.y;
            // }
            copyContent = new StringBuffer();

            // TODO 优化复制，将for循环中的一些方法调用抽取出来，换成变量直接使用
            int marginLeft = settings.getMarginLeft();// 左边距
            int textSize = settings.getTextSize(); // 正文的字体大小
            float lineSpace = settings.getLineSpace();// 行间距
            int paragraphSpace = settings.getmParagraphSpace();// 段间距
            // 正文距离标题的距离
            // 标题距离上一段段末的距离

            // TODO 解析复制的内容 获取标题 和 段间距 的标记
            for (int i = 0, k = 0, v = 0; i < copyContentList.size(); i++) {
                BookContentLineInfo lineInfo = copyContentList.get(i);
                String text = lineInfo.getContent();
                float dyTop;
                float dyBottom;
                int startIndex = 0, endIndex = 0;
                // -----------------遇到段落的标志处理方案--------------------
                if ("sq|pgh".equals(text)) {
                    k++;
                    if (longy < (y + (i + 1 - k) * textSize + (i + 1 - k) * lineSpace + textSize
                            / 6 + (k - v) * paragraphSpace)
                            && longy > (y + (i + 1 - k) * textSize + (i - k) * lineSpace + textSize
                                    / 6 + (k - v - 1) * paragraphSpace)) {
                        onViewCopyModeCompleted();
                        return;
                    }
                    if (longy < y) {
                        Log4an.i("youyang", "长按区域高度比每一页第一行要高 ");
                        onViewCopyModeCompleted();
                        return;
                    }
                    continue;
                }

                if (i == 1 && k == 1) {
                    dyTop = // 游标在第一行字距离顶部的高度 防止段落标志在第一行 正文从第二行开始的情况
                            y + textSize / 6;
                    v = 1;
                } else {
                    dyTop = // 第一行字距离顶部的高度+ 每一行字的高度之和 + 每一个行间距的和 +1/6的字体大小
                            y + (i - k) * textSize + (i - k) * lineSpace + textSize / 6 + (k - v)
                                    * paragraphSpace;
                }
                // -----------------遇到段落的标志处理方案--------------------
                dyBottom = dyTop + textSize;
                // Log4an.i(TAG, "=======lineInfo.getLineType()"+lineInfo.getLineType());
                if ("0".equals(lineInfo.getLineType() + "")
                        && dyBottom + lineSpace / 2f >= startPoint.y
                        && dyTop - lineSpace / 2f <= endPoint.y
                        // 选中区域的第一行在段首的情况
                        || "2".equals(lineInfo.getLineType() + "")
                        && dyTop - paragraphSpace <= endPoint.y
                        && dyBottom + lineSpace / 2f >= startPoint.y
                        ||
                        // 选中区域的最后一行在段尾的情况
                        "3".equals(lineInfo.getLineType() + "")
                        && dyTop - lineSpace / 2f <= endPoint.y
                        && dyBottom + paragraphSpace >= startPoint.y

                ) {// 复制的开始按钮和结束按钮之间
                   // Log4an.i("yyyy", "走了整个的判断流程");
                    if ("0".equals(lineInfo.getLineType() + "")
                            && dyTop - lineSpace / 2f <= startPoint.y
                            && dyBottom + lineSpace / 2f > endPoint.y
                            // 段首的情况
                            || "2".equals(lineInfo.getLineType() + "")
                            && dyTop - paragraphSpace / 2f - lineSpace / 5 <= startPoint.y
                            && dyBottom + lineSpace / 2f > endPoint.y
                            ||
                            // 段尾的情况
                            "3".equals(lineInfo.getLineType() + "")
                            && dyTop - lineSpace / 2f <= startPoint.y
                            && dyBottom + paragraphSpace / 2f + lineSpace / 5 > endPoint.y
                            // 加入段间距后的处理，当低于最后一行时
                            || (dyTop - lineSpace / 2f <= startPoint.y && ((i == copyContentList
                                    .size() - 1 || ("sq|pgh".equals(copyContentList.get(
                                    copyContentList.size() - 1).getContent()) && i == copyContentList
                                    .size() - 2)) && dyBottom + lineSpace / 2f < endPoint.y))) {// 开始和结束在一行时

                        // Log4an.i(TAG, "text：" + "结束" + text + "结束");
                        switch (handleMode) {
                            case 1:
                                if (startPoint.x >= endPoint.x) {
                                    startPoint.x = endPoint.x - 0.1f;
                                }
                                break;
                            case 0:
                            case 2:
                                if (endPoint.x <= startPoint.x) {
                                    endPoint.x = startPoint.x + 0.1f;
                                }
                                break;
                        }

                        for (int j = 0; j < lineInfo.getContent().length() + 1; j++) {
                            // 起点和终点在一条线上时 判断左边游标滑到哪一个字的位置，到该位置后给startindex赋值
                            if (startPoint.x < marginLeft + getStringWidth(lineInfo, 0, j)) {
                                p1X =
                                        marginLeft
                                                + ((j - 1) < 1 ? 0 : getStringWidth(lineInfo, 0,
                                                        j - 1)) + 1;

                                startIndex = (j - 1) < 1 ? 0 : (j - 1);
                                break;
                            }
                        }
                        for (int j = 0; j < lineInfo.getContent().length() + 1; j++) {
                            // 起点和终点在一条线上时 判断右边游标滑到哪一个字的位置，到该位置后给endindex赋值
                            if (endPoint.x <= marginLeft + getStringWidth(lineInfo, 0, j)) {
                                p2X = marginLeft + getStringWidth(lineInfo, 0, j);
                                endIndex = j;
                                break;
                            }
                        }
                        // 如果左边游标x值大于等于 左边距+一行字的宽度
                        if (startPoint.x >= marginLeft + getStringWidth(lineInfo)) {
                            p1X =
                                    marginLeft
                                            + (lineInfo.getContent().length() == 0 ? getStringWidth(lineInfo)
                                                    : getStringWidth(lineInfo, 0, lineInfo
                                                            .getContent().length() - 1));
                            startIndex =
                                    lineInfo.getContent().length() == 0 ? 0 : (lineInfo
                                            .getContent().length() - 1);
                        }

                        // 直接长按段首的两个空格区域
                        if ("2".equals(lineInfo.getLineType() + "")// "2".equals(lineInfo.getLineType())
                                && longx < marginLeft + textSize * 2
                                && text.length() != text.replaceAll("\\s", "").length()) {
                            return;
                        }

                        if (endPoint.x < marginLeft) {
                            // 当结束点的横坐标小于左边距时,游标结束点的endindex为1个字符长度+左边距
                            p2X =
                                    marginLeft + lineInfo.getContent().length() == 0 ? 0
                                            : getStringWidth(lineInfo, 0, 1);


                            endIndex = lineInfo.getContent().length() == 0 ? 0 : 1;
                        } else if (endPoint.x >= marginLeft + getStringWidth(lineInfo)) {
                            // 当结束点的横坐标大于左边距+一行字的长度时 游标结束点横坐标等于一行字的长度
                            p2X = marginLeft + getStringWidth(lineInfo);
                            endIndex = lineInfo.getContent().length();
                        }

                        copyContent.append(lineInfo.getContent().substring(startIndex, endIndex));
                        // Log4an.i(TAG, "canvas.drawRect-----------------------1： p1X:" + p1X
                        // + ",dyTop:" + dyTop);

                        if ("2".equals(lineInfo.getLineType() + "")// "2".equals(lineInfo.getLineType()+"")
                                && p1X < marginLeft + 2 * textSize) {
                            Log4an.i(TAG, "lineInfo.getLineType():" + lineInfo.getLineType());
                            p1X = marginLeft + 2 * textSize;
                            if (startPoint.x < p1X) {
                                startPoint.x = p1X;
                            }
                            canvas.drawRect(marginLeft + 2 * textSize, dyTop, p2X, dyBottom, paint);
                        } else {
                            canvas.drawRect(p1X, dyTop, p2X, dyBottom, paint);
                        }
                        /*
                         * if (dyTop - lineSpace / 2f <= startPoint.y && dyBottom + lineSpace / 2f >
                         * endPoint.y)
                         */

                    } else if ("0".equals(lineInfo.getLineType() + "")
                            && dyTop - lineSpace / 2f <= startPoint.y
                            || "2".equals(lineInfo.getLineType() + "")
                            && dyTop - paragraphSpace / 2f - lineSpace / 5 <= startPoint.y
                            || "3".equals(lineInfo.getLineType() + "")
                            && dyTop - lineSpace / 2f <= startPoint.y) {// 到了开始按钮对应的这一行
                        for (int j = 0; j < lineInfo.getContent().length() + 1; j++) {
                            if (startPoint.x < marginLeft + getStringWidth(lineInfo, 0, j)) {
                                // 找到起始坐标 然后画出从起始坐标到行末的 蓝色渲染着色
                                // Log4an.i(TAG, "canvas.drawRect-----------------------2： p1X:" +
                                // p1X
                                // + ",dyTop:" + dyTop);

                                if ("2".equals(lineInfo.getLineType() + "")
                                        && p1X < marginLeft + 2 * textSize) {
                                    if (startPoint.x < marginLeft + 2 * textSize) {
                                        p1X = marginLeft + 2 * textSize;
                                        startPoint.x = marginLeft + 2 * textSize;
                                        canvas.drawRect(marginLeft + 2 * textSize, dyTop,
                                                marginLeft + getStringWidth(lineInfo), dyBottom,
                                                paint);
                                    } else {
                                        canvas.drawRect(
                                                marginLeft
                                                        + ((j - 1) < 1 ? 0 : getStringWidth(
                                                                lineInfo, 0, j - 1)), dyTop,
                                                marginLeft + getStringWidth(lineInfo), dyBottom,
                                                paint);
                                        p1X =
                                                marginLeft
                                                        + ((j - 1) < 1 ? 0 : getStringWidth(
                                                                lineInfo, 0, j - 1)) + 1;
                                        startIndex = j - 1 < 0 ? 0 : (j - 1);
                                    }
                                } else {
                                    canvas.drawRect(
                                            marginLeft
                                                    + ((j - 1) < 1 ? 0 : getStringWidth(lineInfo,
                                                            0, j - 1)), dyTop, marginLeft
                                                    + getStringWidth(lineInfo), dyBottom, paint);
                                    p1X =
                                            marginLeft
                                                    + ((j - 1) < 1 ? 0 : getStringWidth(lineInfo,
                                                            0, j - 1)) + 1;
                                    startIndex = j - 1 < 0 ? 0 : (j - 1);
                                }
                                break;
                            }
                        }
                        // 横坐标大于一行的长度+左边间距
                        if (startPoint.x >= marginLeft + getStringWidth(lineInfo)) {
                            p1X =
                                    marginLeft
                                            + (lineInfo.getContent().length() == 0 ? getStringWidth(lineInfo)
                                                    : getStringWidth(lineInfo, 0, lineInfo
                                                            .getContent().length() - 1));
                            // Log4an.i(TAG, "canvas.drawRect-----------------------3： p1X:" + p1X
                            // + ",dyTop:" + dyTop);
                            canvas.drawRect(p1X, dyTop, marginLeft + getStringWidth(lineInfo),
                                    dyBottom, paint);
                            startIndex =
                                    lineInfo.getContent().length() == 0 ? 0 : (lineInfo
                                            .getContent().length() - 1);
                        }
                        // 将这一行的数据中 游标选取的字符串 保存起来
                        copyContent.append(lineInfo.getContent().substring(startIndex));
                    } else if ("0".equals(lineInfo.getLineType() + "")
                            && dyBottom + lineSpace / 2f >= endPoint.y
                            || "2".equals(lineInfo.getLineType() + "")
                            && dyBottom + lineSpace / 2f >= endPoint.y
                            || "3".equals(lineInfo.getLineType() + "")
                            && dyBottom + paragraphSpace / 2f + lineSpace / 5 >= endPoint.y
                            || (i == copyContentList.size() - 1 || ("sq|pgh".equals(copyContentList
                                    .get(copyContentList.size() - 1).getContent()) && i == copyContentList
                                    .size() - 2)
                                    && dyBottom + lineSpace / 2f <= endPoint.y)) {// 结束按钮
                        for (int j = 1; j < lineInfo.getContent().length() + 1; j++) {
                            // 到了最后一行 右游标的分割点 得到结束点的 endindex
                            if (endPoint.x <= marginLeft + getStringWidth(lineInfo, 0, j)) {
                                // Log4an.i(TAG, "canvas.drawRect-----------------------4： p1X:" +
                                // p1X
                                // + ",dyTop:" + dyTop);

                                if ("2".equals(lineInfo.getLineType() + "")) {
                                    if (endPoint.x < marginLeft + 2 * textSize) {
                                        p2X = marginLeft + 2 * textSize;
                                        endPoint.x = marginLeft + 2 * textSize;
                                    } else {
                                        p2X = marginLeft + getStringWidth(lineInfo, 0, j);
                                    }
                                    canvas.drawRect(marginLeft + 2 * textSize, dyTop, marginLeft
                                            + getStringWidth(lineInfo, 0, j), dyBottom, paint);
                                } else {
                                    canvas.drawRect(marginLeft, dyTop,
                                            marginLeft + getStringWidth(lineInfo, 0, j), dyBottom,
                                            paint);
                                    p2X = marginLeft + getStringWidth(lineInfo, 0, j);
                                }
                                endIndex = j;
                                break;
                            }
                        }

                        // 小于左边界
                        if (endPoint.x < marginLeft && lineInfo.getContent().length() == 0) {
                            p2X = marginLeft;
                        }
                        // 大于右边界
                        if (endPoint.x > marginLeft + getStringWidth(lineInfo)) {
                            // Log4an.i(TAG, "canvas.drawRect-----------------------5： p1X:" + p1X
                            // + ",dyTop:" + dyTop);
                            canvas.drawRect(marginLeft, dyTop, marginLeft
                                    + getStringWidth(lineInfo), dyBottom, paint);
                            p2X = marginLeft + getStringWidth(lineInfo);
                            endIndex = lineInfo.getContent().length();
                        }
                        // 添加最后一行的数据
                        copyContent.append(lineInfo.getContent().substring(0, endIndex));
                    }

                    else {
                        // 开始按钮 与结束按钮之间的部分
                        // Log4an.i(TAG, "canvas.drawRect-----------------------6： p1X:" + p1X
                        // + ",dyTop:" + dyTop);

                        if ("2".equals(lineInfo.getLineType() + "")) {
                            // if(dyTop-paragraphSpace+lineSpace/2f<=startPoint.y){
                            // canvas.drawRect(p1X, dyTop, marginLeft
                            // + getStringWidth(lineInfo), dyBottom, paint);
                            // }else{
                            canvas.drawRect(marginLeft + 2 * textSize, dyTop, marginLeft
                                    + getStringWidth(lineInfo), dyBottom, paint);
                            // }

                        } else {
                            canvas.drawRect(marginLeft, dyTop, marginLeft
                                    + getStringWidth(lineInfo), dyBottom, paint);
                        }
                        copyContent.append(lineInfo.getContent());
                    }
                    if (p1Y < 0) {
                        // 左按钮的 y坐标
                        p1Y = dyTop;
                    }
                    p2Y = dyBottom - (lineSpace == 0 ? 1 : 0);
                }
                // Log4an.i("yyyy", "走完整个的判断流程之后会执行的动作");
                // Log4an.i("youyang", "longy" + longy);
                // Log4an.i("youyang", "dyBottom: " + dyBottom);

                if ("sq|pgh".equals(copyContentList.get(copyContentList.size() - 1).getContent())) {
                    if (i == copyContentList.size() - 2) {
                        if (longy > dyBottom) {
                            Log4an.i("youyang", "长按区域高度比每一页最后一行更低 ");
                            onViewCopyModeCompleted();
                            return;
                        }
                    }
                }

                // 如果最后一行是段落标志的话，逻辑不会走到这一行
                if (i == copyContentList.size() - 1) {
                    if (longy > dyBottom) {
                        Log4an.i("youyang", "长按区域高度比每一页最后一行更低 ");
                        onViewCopyModeCompleted();
                        return;
                    }

                }
            }
            if (p1X >= 0) {
                startPoint.x = p1X;
            }
            if (p1Y >= 0) {
                startPoint.y = p1Y;
            }
            if (p2X >= 0) {
                endPoint.x = p2X;
            }
            if (p2Y >= 0) {
                endPoint.y = p2Y;
            }
            mBookContentView.setDefaultPagePicture(cachePicture);
            paint.setColor(color);
        }

        // 复制模式更新控件
        if (settings.isCopyMode()) {
            if (getBookContentInfo() != null && "net".equals(getBookContentInfo().getType())) {
                // Log4an.i(TAG, "复制模式更新控件1");
                mBookContentView.showOrUpdateCopyController(startPoint, endPoint, true);
            } else {
                // Log4an.i(TAG, "复制模式更新控件2");
                mBookContentView.showOrUpdateCopyController(startPoint, endPoint, false);
            }
            mBookContentView.postInvalidate();
        } else {
            mBookContentView.postInvalidate();
        }
    }

    // TODO
    /** 获取复制模式的复制内容 */
    public String getCopyContent() {
        if (copyContent != null) {
            return copyContent.toString();
        }
        return null;
    }

    @Override
    public void onViewInLongClickTouching(float startX, float startY, float endX, float endY,
            int handleMode, float longDownY, float longDownX) {
        setStartPoint(startX, startY);
        setEndPoint(endX, endY);
        if (mBookContentView.getPageTurnMode() == BookContentView.PAGETURN_MODE_SMOOTH) {
            // mBookContentRender.mScrollOffset = 0;
            drawCopyMode(handleMode, longDownX, longDownY);
        } else {
            mBookContentRender.mScrollOffset = 0;
            drawCopyMode(handleMode, longDownX, longDownY);
        }
    }

    @Override
    public void onViewCopyModeCompleted() {
        if (settings.isCopyMode()) {
            settings.setCopyMode(false);
            mBookContentView.dismissCopyController();
            // cachePicture.draw(canvas);
            notifyUpdateContentChanged();
        }
    }

    /** 通知更新默认画面 */
    public void notifyUpdateContentChanged() {
        try {
            if (getCurLines() == null || getCurLines().size() == 0)
                return;
            if (getCurLines() == null && index + linesNum - 1 <= 0)
                return;
            if (getCurLines() == null && index >= getCurLines().size())
                return;
            linesNum = settings.getScreenVisibleLineNum();
            if (mBookContentView.getPageTurnMode() == BookContentView.PAGETURN_MODE_SMOOTH) {
                mBookContentView.setDefaultPagePicture(defaultPicture2);
                drawCopyMode(0, -1, -1);
            } else {
                mBookContentRender.mScrollOffset = 0;
                // preparePicture(0, 0);
                mBookContentView.setDefaultPagePicture(defaultPicture2);
                drawCopyMode(0, -1, -1);
            }
            // 画面更新完成执行更新菜单数据
            if (mBookContentMenuView != null && mBookContentMenuView.isShown()) {
                mBookContentMenuView.onBookContentComplete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onViewCopyModeClicked(int which) {
        copyContent2 = getCopyContent();
        switch (which) {
            case 0:// 复制
                StatisticsUtils.onEvent(StatisticsEventID.LONGCLICK_COPY);
                if (TextUtils.isEmpty(copyContent2)) {
                    ((BookContentActivity) mContext).showMsg("复制内容为空");
                } else {
                    ClipboardManager clip =
                            (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                    clip.setText(copyContent2);
                    ((BookContentActivity) mContext).showMsg("复制完成");
                }
                onViewCopyModeCompleted();
                break;
            case 1:// 分享
                StatisticsUtils.onEvent(StatisticsEventID.LONGCLICK_SHARE);
                StatisticsUtils.onEvent(StatisticsEventID.LONGCLICK_SHARE);
                ShareModel mShare = new ShareModel(mContext);
                mShare.share(copyContent2, "书旗小说分享", contentUrl, mBookContentInfo.getImageUrl(),
                        mBookContentInfo);
                copyContent2 = "";
                break;
            case 2:// 报错
                   // if (getBookContentInfo() != null) {
                   // new ChapterErrorDialog(mContext).show();
                   // // new ChapterErrorCommitTask(BookContent.this,
                   // // params.getBookid(), params.getChapterid()).execute();
                   // }
                break;
        }
    }

    /** 获取部分字符串的宽度 */
    public float getStringWidth(BookContentLineInfo info) {
        return getStringWidth(info, 0, info.getXys().length);
    }

    /** 获取部分字符串的宽度 */
    public float getStringWidth(BookContentLineInfo info, int start, int end) {
        float d = 0;
        if (end == 0) {
            return 0;
        }
        if (end > info.getContent().length() - 1) {
            end = info.getContent().length() - 1;
            // d = paint.measureText(info.getContent().substring(info.getContent().length() -1));
            d = settings.getTextSize();
            // Log4an.i("youyang", "最后一个字宽度d：："+d+",字的高度::"+settings.getTextSize());
        }
        float width = info.getXys()[end * 2] - info.getXys()[start * 2] + d;
        return width;
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.shuqi.common.utils.onDrawDataListener#getByteIndex()
     */
    @Override
    public int getByteIndex() {
        return (int) mBookContentInfo.getMarkIndex();
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.shuqi.common.utils.onDrawDataListener#actionDirection()
     */
    @Override
    public boolean actionDirection() {
        return actionDirection;
    }
}
